Skip to content
This repository was archived by the owner on Dec 28, 2024. It is now read-only.

Commit a70d8af

Browse files
committed
Refactor day 24 part 1
1 parent 8d56482 commit a70d8af

File tree

1 file changed

+46
-22
lines changed

1 file changed

+46
-22
lines changed

solutions/day24/main.go

+46-22
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,50 @@ func part1(
2020
if err != nil {
2121
return fmt.Sprintf("Failed to parse input: %v", err)
2222
}
23-
zNames := findZIndexes(r, wm)
23+
zNames := findIndexes('z', r, wm)
24+
resolveNames(r, wm, zNames)
25+
out, strOut, err := toInt(r, zNames)
26+
if err != nil {
27+
return fmt.Sprintf("Failed to read %s as binary: %v", strOut, err)
28+
}
29+
30+
return fmt.Sprintf("Decimal output is %d (binary %s)", out, strOut)
31+
}
32+
33+
func toInt(
34+
r registry,
35+
names []name,
36+
) (int, string, error) {
37+
values := make([]string, len(names))
38+
for i, n := range names {
39+
if r[n] {
40+
values[i] = "1"
41+
} else {
42+
values[i] = "0"
43+
}
44+
}
45+
46+
slices.Reverse(values)
47+
outStr := strings.Join(values, "")
48+
out64, err := strconv.ParseInt(outStr, 2, 0)
49+
outInt := int(out64)
50+
if err != nil {
51+
return outInt, outStr, fmt.Errorf("failed to read %s as binary: %v", outStr, err)
52+
}
53+
54+
return outInt, outStr, nil
55+
}
56+
57+
func resolveNames(
58+
r registry,
59+
wm wireMap,
60+
nameSets ...[]name,
61+
) {
2462
depSet := make(map[name]bool)
25-
for _, zName := range zNames {
26-
depSet[zName] = true
63+
for _, nameSet := range nameSets {
64+
for _, n := range nameSet {
65+
depSet[n] = true
66+
}
2767
}
2868

2969
for len(depSet) > 0 {
@@ -40,23 +80,6 @@ func part1(
4080
}
4181
depSet = newDepSet
4282
}
43-
44-
zValues := make([]string, len(zNames))
45-
for i, zName := range zNames {
46-
if r[zName] {
47-
zValues[i] = "1"
48-
} else {
49-
zValues[i] = "0"
50-
}
51-
}
52-
slices.Reverse(zValues)
53-
zString := strings.Join(zValues, "")
54-
out, err := strconv.ParseInt(zString, 2, 0)
55-
if err != nil {
56-
return fmt.Sprintf("Failed to read %s as binary: %v", zString, err)
57-
}
58-
59-
return fmt.Sprintf("Decimal output is %d (binary %s)", out, zString)
6083
}
6184

6285
func resolveDeps(
@@ -101,13 +124,14 @@ func (w wire) execute(
101124
}
102125
}
103126

104-
func findZIndexes(
127+
func findIndexes(
128+
prefix rune,
105129
r registry,
106130
wm wireMap,
107131
) []name {
108132
out := make([]name, 0, 30)
109133
for curr := 0; ; curr++ {
110-
key := name(fmt.Sprintf("z%02d", curr))
134+
key := name(fmt.Sprintf("%c%02d", prefix, curr))
111135
_, inR := r[key]
112136
_, inWM := wm[key]
113137
if !inR && !inWM {

0 commit comments

Comments
 (0)