forked from ga-paul-t/advent-of-code-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathb.go
108 lines (85 loc) · 1.66 KB
/
b.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package day03
import (
"math"
"strconv"
"strings"
)
type PuzzleB struct{}
func (p PuzzleB) String() string {
return "03b"
}
func (p PuzzleB) Run() int {
readings := strings.Split(input, "\n")
bits := len(readings[0])
oxyRating := oxygenRating(readings, bits)
co2Rating := co2Rating(readings, bits)
return int(oxyRating * co2Rating)
}
func oxygenRating(readings []string, bits int) int64 {
for i := 0; i < bits && len(readings) > 2; i++ {
max := int(math.Ceil(float64(len(readings)) / 2.0))
ones, zeros := 0, 0
var b byte = '0'
for _, r := range readings {
if r[i] == '1' {
ones++
} else {
zeros++
}
// Circuit break as quickly as possible
if ones == max || zeros == max {
break
}
}
if ones >= zeros {
b = '1'
}
oxy := []string{}
for _, r := range readings {
if r[i] == b {
oxy = append(oxy, r)
}
}
readings = oxy
}
r := readings[1]
if readings[0][bits-1] == '1' {
r = readings[0]
}
rv, _ := strconv.ParseInt(r, 2, 64)
return rv
}
func co2Rating(readings []string, bits int) int64 {
for i := 0; i < bits && len(readings) > 2; i++ {
max := int(math.Ceil(float64(len(readings)) / 2.0))
ones, zeros := 0, 0
var b byte = '1'
for _, r := range readings {
if r[i] == '1' {
ones++
} else {
zeros++
}
// Circuit break as quickly as possible
if ones == max || zeros == max {
break
}
}
if ones >= zeros {
b = '0'
}
co2 := []string{}
for _, r := range readings {
if r[i] == b {
co2 = append(co2, r)
}
}
readings = co2
}
r := readings[1]
if readings[0][bits-1] == '0' {
r = readings[0]
}
rv, _ := strconv.ParseInt(r, 2, 64)
return rv
}