Solve AOC day 3 pt 2

This commit is contained in:
2021-12-06 14:01:22 -07:00
parent 6ecb87c5ae
commit a898a73f19
2 changed files with 17 additions and 4 deletions

View File

@@ -12,7 +12,8 @@
(day 3 (day 3
(load "day3.kiss") (load "day3.kiss")
(let [inputs (Util.readLines "src/year2021/inputs/day3.txt")] (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 (day 4
(load "day4.kiss") (load "day4.kiss")
(assert (= 4512 (winningScore "src/year2021/inputs/day4-example.txt"))) (assert (= 4512 (winningScore "src/year2021/inputs/day4-example.txt")))

View File

@@ -9,7 +9,7 @@
(assert (= 22 (binaryStringToDecimal "10110"))) (assert (= 22 (binaryStringToDecimal "10110")))
(assert (= 9 (binaryStringToDecimal "10110" true))) (assert (= 9 (binaryStringToDecimal "10110" true)))
(function :String mostCommonBit [:String binary] (function :String mostCommonBit [:String binary &opt :String tieBreaker]
(let [&mut ones 0.0 (let [&mut ones 0.0
&mut total 0.0] &mut total 0.0]
(doFor digit (binary.split "") (doFor digit (binary.split "")
@@ -17,7 +17,9 @@
(case digit (case digit
("1" (+= ones 1)) ("1" (+= ones 1))
(otherwise))) (otherwise)))
(Std.string (Math.round (/ ones total))))) (if (and tieBreaker (= ones (/ total 2)))
tieBreaker
(Std.string (Math.round (/ ones total))))))
(function :Int rate [:Array<String> inputs :Bool epsilon] (function :Int rate [:Array<String> inputs :Bool epsilon]
(binaryStringToDecimal (binaryStringToDecimal
@@ -25,4 +27,14 @@
(for idx (range .length (first inputs)) (for idx (range .length (first inputs))
(mostCommonBit (.join (for input inputs (input.charAt idx)) ""))) (mostCommonBit (.join (for input inputs (input.charAt idx)) "")))
"") "")
epsilon)) epsilon))
// Part 2
(function :Int otherRate [:Array<String> 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)