aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorClyne Sullivan <clyne@bitgloo.com>2022-12-02 05:24:28 -0500
committerClyne Sullivan <clyne@bitgloo.com>2022-12-02 05:24:28 -0500
commitba7234aef9421278ad36bc09e5fddde9af4ce001 (patch)
treef273ad0399437376d4232a39522a7fbed45b8063
parent34a3d91c87aadcf42f6189822eb6e4e2e58e8551 (diff)
add day2
-rw-r--r--day2/part1.forth19
-rw-r--r--day2/part2.forth19
2 files changed, 38 insertions, 0 deletions
diff --git a/day2/part1.forth b/day2/part1.forth
new file mode 100644
index 0000000..b23e418
--- /dev/null
+++ b/day2/part1.forth
@@ -0,0 +1,19 @@
+: next-rpc ( fd -- score-or-false-if-eof )
+ pad 4 rot read-line throw ( read next line from file )
+ swap 3 = and if ( if read complete round )
+ pad 2 + c@ dup 87 - ( score for our hand )
+ swap pad c@ - ( difference between hands )
+ dup 23 = if drop 3 + else ( 3pts for tie e.g. 'X' - 'A' )
+ dup 21 = swap 24 = or if 6 + then ( 6pts for win )
+ then
+ else false then ; ( false if end-of-file )
+
+: all-rpcs ( fd -- total-score )
+ 0 begin ( start with zero score )
+ over next-rpc ( read next hand )
+ dup if + true then ( add to score if not EOF )
+ 0= until nip ;
+
+s" input" r/o open-file throw all-rpcs . cr ( play all rounds in input )
+bye
+
diff --git a/day2/part2.forth b/day2/part2.forth
new file mode 100644
index 0000000..2dc6b13
--- /dev/null
+++ b/day2/part2.forth
@@ -0,0 +1,19 @@
+create outcomes 3 , 4 , 8 , 1 , 5 , 9 , 2 , 6 , 7 , ( AX-Z, BX-Z, CX-Z )
+
+: next-rpc ( fd -- outcome )
+ pad 4 rot read-line throw ( read next line from file )
+ swap 3 = and if ( if read complete round )
+ pad c@ 65 - 3 * ( calculate ABC outcomes index )
+ pad 2 + c@ 88 - + ( add XYZ offset )
+ cells outcomes + @ ( lookup score for the round )
+ else false then ; ( false if end-of-file )
+
+: all-rpcs ( fd -- total-score )
+ 0 begin ( start with zero score )
+ over next-rpc ( read next hand )
+ dup if + true then ( add to score if not EOF )
+ 0= until nip ;
+
+s" input" r/o open-file throw all-rpcs . cr ( play all rounds in input )
+bye
+