diff --git a/projects/aoc/src/year2021/Solutions2021.kiss b/projects/aoc/src/year2021/Solutions2021.kiss index 36e36fe3..01c514b7 100644 --- a/projects/aoc/src/year2021/Solutions2021.kiss +++ b/projects/aoc/src/year2021/Solutions2021.kiss @@ -12,7 +12,8 @@ (day 3 (load "day3.kiss") (let [inputs (Util.readLines "src/year2021/inputs/day3.txt")] - (assert (= 845186 (* (rate inputs false) (rate inputs true)))))) + (assert (= 845186 (* (rate inputs false) (rate inputs true)))) + (assert (= 4636702 (* (otherRate inputs false) (otherRate inputs true)))))) (day 4 (load "day4.kiss") (assert (= 4512 (winningScore "src/year2021/inputs/day4-example.txt"))) diff --git a/projects/aoc/src/year2021/day3.kiss b/projects/aoc/src/year2021/day3.kiss index be00331a..f922998f 100644 --- a/projects/aoc/src/year2021/day3.kiss +++ b/projects/aoc/src/year2021/day3.kiss @@ -9,7 +9,7 @@ (assert (= 22 (binaryStringToDecimal "10110"))) (assert (= 9 (binaryStringToDecimal "10110" true))) -(function :String mostCommonBit [:String binary] +(function :String mostCommonBit [:String binary &opt :String tieBreaker] (let [&mut ones 0.0 &mut total 0.0] (doFor digit (binary.split "") @@ -17,7 +17,9 @@ (case digit ("1" (+= ones 1)) (otherwise))) - (Std.string (Math.round (/ ones total))))) + (if (and tieBreaker (= ones (/ total 2))) + tieBreaker + (Std.string (Math.round (/ ones total)))))) (function :Int rate [:Array inputs :Bool epsilon] (binaryStringToDecimal @@ -25,4 +27,14 @@ (for idx (range .length (first inputs)) (mostCommonBit (.join (for input inputs (input.charAt idx)) ""))) "") - epsilon)) \ No newline at end of file + epsilon)) + +// Part 2 +(function :Int otherRate [:Array inputs :Bool co2] + (doFor idx (range .length (first inputs)) + (let [mcb (mostCommonBit (.join (for input inputs (input.charAt idx)) "") "1") + o2filter ->input (= (input.charAt idx) mcb) + co2Filter ->input !(o2filter input)] + (set inputs (filter inputs (if co2 co2Filter o2filter)))) + (when (= 1 inputs.length) (return (binaryStringToDecimal (first inputs))))) + null) \ No newline at end of file