Skip to content

Commit

Permalink
Solved day 2 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
gdejong committed Dec 5, 2024
1 parent 90c20a6 commit 314dac2
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
43 changes: 41 additions & 2 deletions cmd/day2/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/gdejong/advent-of-code-2024/internal/math"
"github.com/gdejong/advent-of-code-2024/internal/must"
"github.com/gdejong/advent-of-code-2024/internal/slices"
"io"
"os"
"strings"
)
Expand All @@ -15,6 +16,11 @@ func main() {
f := must.NoError(os.Open("cmd/day2/real_input.txt"))

fmt.Println(part1(f))

// Reset the file so we can it again for part 2
must.NoError(f.Seek(0, io.SeekStart))

fmt.Println(part2(f))
}

func part1(f *os.File) int {
Expand All @@ -24,16 +30,49 @@ func part1(f *os.File) int {
for s.Scan() {
line := s.Text()

levels := input.ToIntegers(strings.Fields(line))
report := input.ToIntegers(strings.Fields(line))

if isSafeReport(levels) {
if isSafeReport(report) {
safeCounter++
}
}

return safeCounter
}

func part2(f *os.File) int {
s := bufio.NewScanner(f)

safeCounter := 0
for s.Scan() {
line := s.Text()

report := input.ToIntegers(strings.Fields(line))

// Create all possible options by continually removing one level
var reportsToCheck [][]int
reportsToCheck = append(reportsToCheck, report)
for index := range len(report) {
reportsToCheck = append(reportsToCheck, remove(report, index))
}

for _, r := range reportsToCheck {
if isSafeReport(r) {
safeCounter++
break
}
}
}

return safeCounter
}

func remove(slice []int, s int) []int {
s2 := make([]int, len(slice))
copy(s2, slice)
return append(s2[:s], s2[s+1:]...)
}

func isSafeReport(levels []int) bool {
// Calculate the differences
diffs := make([]int, len(levels)-1)
Expand Down
10 changes: 10 additions & 0 deletions cmd/day2/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,13 @@ func TestPart1(t *testing.T) {
t.Errorf("wrong answer, got: %d", answer)
}
}

func TestPart2(t *testing.T) {
f := must.NoError(os.Open("test_input.txt"))

answer := part2(f)

if answer != 4 {
t.Errorf("wrong answer, got: %d", answer)
}
}

0 comments on commit 314dac2

Please sign in to comment.