Skip to content

Commit e2a6ad9

Browse files
committed
day 3 part 2
1 parent 832775c commit e2a6ad9

File tree

1 file changed

+61
-31
lines changed

1 file changed

+61
-31
lines changed

03/main.go

Lines changed: 61 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -16,49 +16,79 @@ func main() {
1616
}
1717
inputstrarr := strings.Split(input, "\n")
1818

19-
gamma, epsilon := getShit(inputstrarr)
20-
fmt.Printf("Answer: %d\n", gamma*epsilon)
19+
ox, co2 := getShit(inputstrarr)
20+
fmt.Printf("Answer: %d\n", ox*co2)
2121
}
2222

23-
func getShit(vals []string) (gamma int, epsilon int) {
24-
// This loops over the length of each binary
25-
gammaBin := ""
26-
epsilonBin := ""
23+
func getShit(vals []string) (ox int, co2 int) {
24+
// This function should call getVal for oxygen number (most common bitwise)
25+
// And for the co2 number (least common bitwise)
26+
// Then return both
27+
28+
oxBin := getVal(vals, true)
29+
co2bin := getVal(vals, false)
30+
31+
fmt.Println(oxBin)
32+
oxInt, err := strconv.ParseInt(oxBin, 2, 32)
33+
if err != nil {
34+
panic(err)
35+
}
36+
ox = int(oxInt)
37+
38+
fmt.Println(co2bin)
39+
co2Int, err := strconv.ParseInt(co2bin, 2, 32)
40+
if err != nil {
41+
panic(err)
42+
}
43+
co2 = int(co2Int)
44+
45+
return ox, co2
46+
}
47+
48+
// gelVal gets a value based on the most common bit selector, or least common if false.
49+
func getVal(vals []string, mostCommon bool) string {
2750
for i := 0; i < len(vals[0]); i++ {
51+
if len(vals) == 1 {
52+
return vals[0]
53+
}
54+
2855
// This loops over all values in the vals array.
29-
count1 := 0
30-
count0 := 0
56+
filtered1 := []string{}
57+
filtered0 := []string{}
3158
for a := 0; a < len(vals); a++ {
3259
switch string(vals[a][i]) {
3360
case "1":
34-
count1++
61+
filtered1 = append(filtered1, vals[a])
3562
case "0":
36-
count0++
63+
filtered0 = append(filtered0, vals[a])
3764
}
3865
}
3966

40-
if count0 > count1 {
41-
gammaBin = gammaBin + "0"
42-
epsilonBin = epsilonBin + "1"
67+
if mostCommon {
68+
if len(filtered1) > len(filtered0) {
69+
vals = filtered1
70+
continue
71+
}
72+
if len(filtered0) > len(filtered1) {
73+
vals = filtered0
74+
continue
75+
}
76+
// if equal, return 1?
77+
vals = filtered1
78+
continue
4379
} else {
44-
gammaBin = gammaBin + "1"
45-
epsilonBin = epsilonBin + "0"
80+
if len(filtered1) < len(filtered0) {
81+
vals = filtered1
82+
continue
83+
}
84+
if len(filtered0) < len(filtered1) {
85+
vals = filtered0
86+
continue
87+
}
88+
// if equal, return 0?
89+
vals = filtered0
90+
continue
4691
}
4792
}
48-
49-
fmt.Println(gammaBin)
50-
gammaInt, err := strconv.ParseInt(gammaBin, 2, 32)
51-
if err != nil {
52-
panic(err)
53-
}
54-
gamma = int(gammaInt)
55-
56-
fmt.Println(epsilonBin)
57-
epsilonInt, err := strconv.ParseInt(epsilonBin, 2, 32)
58-
if err != nil {
59-
panic(err)
60-
}
61-
epsilon = int(epsilonInt)
62-
63-
return gamma, epsilon
93+
return vals[0]
6494
}

0 commit comments

Comments
 (0)