Skip to content

Commit

Permalink
feat(2024): add day 5 part 1
Browse files Browse the repository at this point in the history
  • Loading branch information
believer committed Dec 5, 2024
1 parent 0556b78 commit 2e41c5f
Show file tree
Hide file tree
Showing 3 changed files with 122 additions and 0 deletions.
59 changes: 59 additions & 0 deletions go/2024/puzzles/day05/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package main

import (
"fmt"
"slices"
"strings"

"github.com/believer/aoc-2024/utils"
"github.com/believer/aoc-2024/utils/files"
)

// There are things that can be improved. I think we can use
// the slices.SortFunc in some way for part 2 as well, but no
// time now.
func main() {
fmt.Println("Part 1: ", part1("input.txt"))
fmt.Println("Part 2: ", part2("input.txt"))
}

func part1(name string) int {
parts := files.ReadParagraphs(name)
total := 0
orderingRules := map[string][]string{}
updates := parts[1]

for _, r := range parts[0] {
parts := strings.Split(r, "|")

orderingRules[parts[0]] = append(orderingRules[parts[0]], parts[1])
}

for _, u := range updates {
isValid := true
pages := strings.Split(u, ",")

for i, p := range pages {
if i+1 > len(pages) {
continue
}

before := pages[:i]
rules := orderingRules[p]

for _, r := range rules {
if slices.Contains(before, r) {
isValid = false
}
}
}

if isValid {
middle := pages[len(pages)/2]

total += utils.MustIntFromString(middle)
}
}

return total
}
35 changes: 35 additions & 0 deletions go/2024/puzzles/day05/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package main

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestPart1(t *testing.T) {
t.Run("Part 1", func(t *testing.T) {
expected := 143
actual := part1("test-input.txt")
assert.Equal(t, expected, actual)
})
}

func TestPart2(t *testing.T) {
t.Run("Part 2", func(t *testing.T) {
expected := 123
actual := part2("test-input.txt")
assert.Equal(t, expected, actual)
})
}

func BenchmarkPart1(b *testing.B) {
for i := 0; i < b.N; i++ {
part1("input.txt")
}
}

func BenchmarkPart2(b *testing.B) {
for i := 0; i < b.N; i++ {
part2("input.txt")
}
}
28 changes: 28 additions & 0 deletions go/2024/puzzles/day05/test-input.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
47|53
97|13
97|61
97|47
75|29
61|13
75|53
29|13
97|29
53|29
61|53
97|53
61|29
47|13
75|47
97|75
47|61
75|61
47|29
75|13
53|13

75,47,61,53,29
97,61,53,29,13
75,29,13
75,97,47,61,53
61,13,29
97,13,75,29,47

0 comments on commit 2e41c5f

Please sign in to comment.