Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

feat: Generate boilerplate for 2024/day02 #341

Draft
wants to merge 9 commits into
base: master
Choose a base branch
from
Prev Previous commit
feat: Implement part 2
  • Loading branch information
obalunenko committed Feb 17, 2025
commit 47c7f8718cfc63cfa94fa912a49585c356ff8a6d
95 changes: 93 additions & 2 deletions internal/puzzles/solutions/2024/day02/solution.go
Original file line number Diff line number Diff line change
@@ -88,6 +88,97 @@ func (s solution) Part1(input io.Reader) (string, error) {
return strconv.Itoa(safeCount), nil
}

func (s solution) Part2(_ io.Reader) (string, error) {
return "", puzzles.ErrNotImplemented
func (s solution) Part2(input io.Reader) (string, error) {
scanner := bufio.NewScanner(input)

isSafe := func(line []int) bool {
var asc, desc bool

removedCount := 0

mayRemove := func(i int) bool {
if removedCount != 0 {
return false
}

removedCount++

return true
}

for i := range line {
if i == len(line)-1 {

}

if line[i-1] < val {
if desc {
return false
}

asc = true
}

if line[i-1] > val {
if asc {
return false
}

desc = true
}

diff := val - line[i-1]
if diff < 0 {
diff = -diff
}

if diff < 1 || diff > 3 {
if !mayRemove(i) {
diff = line[i-1] - line[i+1]
if diff < 0 {
diff = -diff
}

if diff < 1 || diff > 3 {
return false
}

continue
}

return false
}
}

return true
}

var safeCount int

for scanner.Scan() {
line := scanner.Bytes()

numbers, err := utils.ParseInts(bytes.NewReader(line), " ")
if err != nil {
return "", fmt.Errorf("failed to parse input line: %w", err)
}

if isSafe(numbers) {
safeCount++
}
}

if err := scanner.Err(); err != nil {
return "", fmt.Errorf("failed to read input: %w", err)
}

return strconv.Itoa(safeCount), nil
}

func removeIndex(s []int, index int) []int {
ret := make([]int, 0, len(s)-1)

ret = append(ret, s[:index]...)

return append(ret, s[index+1:]...)
}
Loading