From 78311953c703cb6090f461b7cfbdb7d1f5bcb20b Mon Sep 17 00:00:00 2001 From: Vivianne Langdon Date: Mon, 4 Dec 2023 23:38:38 -0500 Subject: [PATCH] Little tweakings --- p02.janet | 43 ++++++++++++++++++++++++------------------- 1 file changed, 24 insertions(+), 19 deletions(-) diff --git a/p02.janet b/p02.janet index d0a913a..84fc1ca 100755 --- a/p02.janet +++ b/p02.janet @@ -14,32 +14,37 @@ (defn pmatch [input] (peg/match peg input)) -(defn color-possible - "Check if a single die count and color pair is possible given the pool of dice" - [pair pool] - (var [count color] pair) - (>= (pool color) count)) +(defn subset-pred + "Check a predicate against a subset" + [subset pred] + (all (fn [pair] (pred pair)) subset)) -(defn possible - "Check if a subset of the dice in the bag is possible given the pool of dice" - [subset pool] - (all (fn [pair] (color-possible pair pool)) subset)) - -(defn all-possible - "Check if all subsets are possible" - [subsets pool] - (all (fn [subset] (possible subset pool)) subsets)) +(defn all-pred + "Check if all subsets satisfy a predicate" + [subsets pred] + (all (fn [subset] (subset-pred subset pred)) subsets)) (def die-pool @{:red 12 :green 13 :blue 14}) +(defn possible + "Check if die fits in the die pool" + [pair] + (var [count color] pair) + (<= count (die-pool color))) + +(defn all-possible + "Check if all fit the pool" + [subsets] + (all-pred subsets possible)) + (defn solve [lines] (var sum 0) (each line lines (var [game subsets] (pmatch line)) - (if (all-possible subsets die-pool) + (if (all-possible subsets) (do (print "Game " game " is good") (+= sum game)))) @@ -59,8 +64,8 @@ @[@[3 :green]]]] (pmatch "Game 42: 1 blue, 4 red; 3 green"))) -(assert (color-possible @[12 :blue] die-pool)) -(assert (not (color-possible @[25 :blue] die-pool))) +(assert (possible @[12 :blue])) +(assert (not (possible @[25 :blue]))) (def impossible-match (pmatch "Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red")) @@ -68,8 +73,8 @@ (def possible-match (pmatch "Game 3: 8 green, 6 blue, 10 red; 5 blue, 4 red, 13 green; 5 green, 1 red")) -(assert (not (all-possible (impossible-match 1) die-pool))) -(assert (all-possible (possible-match 1) die-pool)) +(assert (not (all-possible (impossible-match 1)))) +(assert (all-possible (possible-match 1))) (end-suite)