day25.ps (2493B)
1 %!PS 2 % 3 % Copyright (c) 2022, Natacha Porté 4 % 5 % Permission to use, copy, modify, and distribute this software for any 6 % purpose with or without fee is hereby granted, provided that the above 7 % copyright notice and this permission notice appear in all copies. 8 % 9 % THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 10 % WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 11 % MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 12 % ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 13 % WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 14 % ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 15 % OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 16 % 17 % Usage: 18 % gs -q- -sDEVICE=png16m -o- day25.ps <day25.txt | display 19 20 /datafile (%stdin) (r) file def 21 /stderr (%stderr) (w) file def 22 23 /char-to-digit << 24 61 -2 25 45 -1 26 48 0 27 49 1 28 50 2 29 >> def 30 31 /digit-to-char (=-0123) def 32 33 % (num) -> num 34 /read-snafu { 35 0 exch { 36 % prev-acc digit-char 37 char-to-digit exch get 38 % prev-acc digit-vaue 39 exch 5 mul add 40 % acc 41 } forall 42 % result 43 } bind def 44 45 % num -> (num) 46 /write-snafu { 47 [ exch 0 exch 48 { 49 % ... carry remainder 50 dup 0 eq { pop exit } if 51 % ... carry remainder 52 dup 5 idiv 3 1 roll 53 % ... next-remainder carry remainder 54 5 mod add 55 % ... next-remainder cur-abs-digit 56 0 exch 57 % ... next-remainder next-carry cur-abs-digit 58 { 59 dup 2 le { exit } if 60 exch 1 add exch 5 sub 61 } loop 62 % ... next-remainder next-carry cur-digit 63 3 1 roll exch 64 % ... cur-digit next-carry next-remainder 65 } loop 66 dup 0 eq { pop } if 67 ] 68 % reverse-digit-array 69 dup length string 70 % reverse-digit-array result 71 0 1 2 index length 1 sub { 72 % reverse-digit-array result index 73 2 index length 1 sub 1 index sub 74 % reverse-digit-array result index reverse-index 75 3 index exch get 76 % reverse-digit-array result index cur-digit 77 2 add digit-to-char exch get 78 % reverse-digit-array result index cur-digit-char 79 2 index 3 1 roll put 80 % reverse-digit-array result 81 } for 82 % reverse-digit-array result 83 exch pop 84 } bind def 85 86 /data [ 87 { 88 datafile 200 string readline 89 not { pop exit } if 90 % line 91 read-snafu 92 } loop 93 ] def 94 95 96 97 /Helvetica 20 selectfont 98 99 100 (First Puzzle: ) 101 72 700 moveto show 102 103 0 data { add } forall 104 % sum 105 write-snafu 106 % (sum) 107 show 108 109 showpage 110 quit