application/octet-stream
•
1.66 KB
•
49 lines
#!/usr/bin/env nujel
[def example-data "00100\n11110\n10110\n10111\n10101\n01111\n00111\n11100\n10000\n11001\n00010\n01010"]
[def input-data [file/read "tests/fast/day3.input"]]
[defun read-data [lines]
[map [split lines "\n"]
[λ [line]
[car [read [cat "#b" line]]]]]]
[defun count-bits/single [number state bit-count]
[def i 0]
[while [< i bit-count]
[def mask [ash 1 i]]
[when [zero? [logand number mask]]
[array/set! state i [+ 1 [state i]]]]
[++ i]]]
[defun count-bits [numbers bit-count]
[def count 0]
[def state [array/allocate bit-count]]
[array/fill! state 0]
[while numbers
[count-bits/single [car numbers] state bit-count]
[cdr! numbers]
[++ count]]
@[:bit-count bit-count :count count :zeroes state]]
[defun calc-γε [state]
[def i 0]
[def γ 0]
[def ε 0]
[def threshold [ash [tree/get state :count] -1]]
[def arr [tree/get state :zeroes]]
[while [< i [tree/get state :bit-count]]
[if [< [arr i] threshold]
[set! γ [logior γ [ash 1 i]]]
[set! ε [logior ε [ash 1 i]]]]
[++ i]]
@[:γ γ :ε ε :power-consumption [* ε γ]]]
[def result [calc-γε [count-bits [read-data example-data] 5]]]
[when [!= [tree/get result :power-consumption] 198]
[throw [list :wrong-result "Wrong result" result]]]
[def result [calc-γε [count-bits [read-data input-data] 12]]]
[when [!= [tree/get result :power-consumption] 4103154]
[throw [list :wrong-result "Wrong result" result]]]