03: part1+2

This commit is contained in:
ptrcnull 2021-12-03 09:58:04 +01:00
parent 2545346566
commit a72520ee75
4 changed files with 1140 additions and 0 deletions

1000
3/input Normal file

File diff suppressed because it is too large Load diff

39
3/part1.go Normal file
View file

@ -0,0 +1,39 @@
package main
import (
"bufio"
"fmt"
"os"
)
//const entryBits = 12
//const entryBits = 5
func main() {
zeroes := [entryBits]int{}
ones := [entryBits]int{}
s := bufio.NewScanner(os.Stdin)
for s.Scan() {
for i, v := range s.Bytes() {
if v == '0' {
zeroes[i]++
} else {
ones[i]++
}
}
}
gamma := 0
for i := range zeroes {
if ones[i] > zeroes[i] {
gamma |= 1 << (entryBits - i - 1)
}
}
epsilon := gamma ^ ((1 << entryBits) - 1)
fmt.Println(gamma * epsilon)
}

89
3/part2.go Normal file
View file

@ -0,0 +1,89 @@
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)
}

12
3/testinput Normal file
View file

@ -0,0 +1,12 @@
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010