Skip to content

Commit 47c7f87

Browse files
committed
feat: Implement part 2
1 parent 72bf3d4 commit 47c7f87

File tree

1 file changed

+93
-2
lines changed

1 file changed

+93
-2
lines changed

internal/puzzles/solutions/2024/day02/solution.go

Lines changed: 93 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,97 @@ func (s solution) Part1(input io.Reader) (string, error) {
8888
return strconv.Itoa(safeCount), nil
8989
}
9090

91-
func (s solution) Part2(_ io.Reader) (string, error) {
92-
return "", puzzles.ErrNotImplemented
91+
func (s solution) Part2(input io.Reader) (string, error) {
92+
scanner := bufio.NewScanner(input)
93+
94+
isSafe := func(line []int) bool {
95+
var asc, desc bool
96+
97+
removedCount := 0
98+
99+
mayRemove := func(i int) bool {
100+
if removedCount != 0 {
101+
return false
102+
}
103+
104+
removedCount++
105+
106+
return true
107+
}
108+
109+
for i := range line {
110+
if i == len(line)-1 {
111+
112+
}
113+
114+
if line[i-1] < val {
115+
if desc {
116+
return false
117+
}
118+
119+
asc = true
120+
}
121+
122+
if line[i-1] > val {
123+
if asc {
124+
return false
125+
}
126+
127+
desc = true
128+
}
129+
130+
diff := val - line[i-1]
131+
if diff < 0 {
132+
diff = -diff
133+
}
134+
135+
if diff < 1 || diff > 3 {
136+
if !mayRemove(i) {
137+
diff = line[i-1] - line[i+1]
138+
if diff < 0 {
139+
diff = -diff
140+
}
141+
142+
if diff < 1 || diff > 3 {
143+
return false
144+
}
145+
146+
continue
147+
}
148+
149+
return false
150+
}
151+
}
152+
153+
return true
154+
}
155+
156+
var safeCount int
157+
158+
for scanner.Scan() {
159+
line := scanner.Bytes()
160+
161+
numbers, err := utils.ParseInts(bytes.NewReader(line), " ")
162+
if err != nil {
163+
return "", fmt.Errorf("failed to parse input line: %w", err)
164+
}
165+
166+
if isSafe(numbers) {
167+
safeCount++
168+
}
169+
}
170+
171+
if err := scanner.Err(); err != nil {
172+
return "", fmt.Errorf("failed to read input: %w", err)
173+
}
174+
175+
return strconv.Itoa(safeCount), nil
176+
}
177+
178+
func removeIndex(s []int, index int) []int {
179+
ret := make([]int, 0, len(s)-1)
180+
181+
ret = append(ret, s[:index]...)
182+
183+
return append(ret, s[index+1:]...)
93184
}

0 commit comments

Comments
 (0)