57 lines
1.7 KiB
Nim
57 lines
1.7 KiB
Nim
# 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())
|