add day 1 solution part 1
This commit is contained in:
parent
0aaaacd154
commit
d64d0628e5
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,56 @@
|
||||||
|
# Copyright 2021 Christian Ulrich
|
||||||
|
#
|
||||||
|
# This program is free software: you can redistribute it and/or modify
|
||||||
|
# it under the terms of the GNU General Public License as published by
|
||||||
|
# the Free Software Foundation, either version 3 of the License, or
|
||||||
|
# (at your option) any later version.
|
||||||
|
#
|
||||||
|
# This program is distributed in the hope that it will be useful,
|
||||||
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
# GNU General Public License for more details.
|
||||||
|
#
|
||||||
|
# You should have received a copy of the GNU General Public License
|
||||||
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
# usage: ./part1 < input
|
||||||
|
|
||||||
|
proc powerConsumption(): uint64 =
|
||||||
|
var
|
||||||
|
line = ""
|
||||||
|
lineCount = 0'u64
|
||||||
|
bitCounts: seq[uint64]
|
||||||
|
while readLine(stdin, line):
|
||||||
|
if line.len() > 0:
|
||||||
|
if line.len() != bitCounts.len():
|
||||||
|
if bitCounts.len() == 0:
|
||||||
|
newSeq(bitCounts, line.len())
|
||||||
|
else:
|
||||||
|
raise newException(ValueError, "invalid line length")
|
||||||
|
lineCount.inc()
|
||||||
|
for index, digit in line.pairs():
|
||||||
|
case digit
|
||||||
|
of '0': discard
|
||||||
|
of '1': bitCounts[index].inc()
|
||||||
|
else: raise newException(ValueError, "invalid digit")
|
||||||
|
var
|
||||||
|
gamma = 0'u64
|
||||||
|
epsilon = 0'u64
|
||||||
|
for index, bitCount in bitCounts.pairs():
|
||||||
|
let bitPosition = bitCounts.len() - 1 - index
|
||||||
|
let mask = 1'u64 shl uint64(bitPosition)
|
||||||
|
if bitCount > lineCount div 2:
|
||||||
|
gamma = gamma or mask
|
||||||
|
else:
|
||||||
|
epsilon = epsilon or mask
|
||||||
|
result = gamma * epsilon
|
||||||
|
|
||||||
|
proc main(): int =
|
||||||
|
try:
|
||||||
|
echo powerConsumption()
|
||||||
|
except Exception as error:
|
||||||
|
echo error.msg
|
||||||
|
result = -1
|
||||||
|
|
||||||
|
when isMainModule:
|
||||||
|
quit(main())
|
|
@ -0,0 +1,12 @@
|
||||||
|
00100
|
||||||
|
11110
|
||||||
|
10110
|
||||||
|
10111
|
||||||
|
10101
|
||||||
|
01111
|
||||||
|
00111
|
||||||
|
11100
|
||||||
|
10000
|
||||||
|
11001
|
||||||
|
00010
|
||||||
|
01010
|
Loading…
Reference in New Issue