89 lines
1.4 KiB
Go
89 lines
1.4 KiB
Go
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"os"
|
|
"strconv"
|
|
)
|
|
|
|
const entryBits = 12
|
|
//const entryBits = 5
|
|
|
|
func nthBit(f int, i int) int {
|
|
a := entryBits - i - 1
|
|
return f & (1 << a) >> a
|
|
}
|
|
|
|
type NumberList []int
|
|
|
|
func (n NumberList) CountBits(index int) (ones int, zeroes int) {
|
|
for _, num := range n {
|
|
if nthBit(num, index) == 1 {
|
|
ones++
|
|
} else {
|
|
zeroes++
|
|
}
|
|
}
|
|
return
|
|
}
|
|
|
|
func (n NumberList) Filter(index int, bit int) NumberList {
|
|
var res NumberList
|
|
for _, num := range n {
|
|
if nthBit(num, index) == bit {
|
|
res = append(res, num)
|
|
}
|
|
}
|
|
return res
|
|
}
|
|
|
|
func main() {
|
|
var numbers NumberList
|
|
|
|
s := bufio.NewScanner(os.Stdin)
|
|
for s.Scan() {
|
|
value, _ := strconv.ParseInt(s.Text(), 2, 64)
|
|
numbers = append(numbers, int(value))
|
|
}
|
|
|
|
oxygenNumbers := numbers
|
|
for i := 0; i < entryBits; i++ {
|
|
ones, zeroes := oxygenNumbers.CountBits(i)
|
|
|
|
var bit int
|
|
if ones >= zeroes {
|
|
bit = 1
|
|
} else {
|
|
bit = 0
|
|
}
|
|
|
|
//fmt.Println(i, bit, zeroes, ones, len(oxygenNumbers))
|
|
oxygenNumbers = oxygenNumbers.Filter(i, bit)
|
|
if len(oxygenNumbers) == 1 {
|
|
break
|
|
}
|
|
}
|
|
oxygen := oxygenNumbers[0]
|
|
|
|
co2Numbers := numbers
|
|
for i := 0; i < entryBits; i++ {
|
|
ones, zeroes := co2Numbers.CountBits(i)
|
|
|
|
var bit int
|
|
if ones < zeroes {
|
|
bit = 1
|
|
} else {
|
|
bit = 0
|
|
}
|
|
|
|
//fmt.Println(i, bit, zeroes, ones, len(co2Numbers))
|
|
co2Numbers = co2Numbers.Filter(i, bit)
|
|
if len(co2Numbers) == 1 {
|
|
break
|
|
}
|
|
}
|
|
co2 := co2Numbers[0]
|
|
|
|
fmt.Println(oxygen * co2)
|
|
}
|