Day 5 done
This commit is contained in:
parent
1bc1eded9d
commit
a005bed378
17
cmd/05/main.go
Normal file
17
cmd/05/main.go
Normal file
@ -0,0 +1,17 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"aoc2024/internal/common"
|
||||
"aoc2024/internal/day05"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Println("Opening file...")
|
||||
bytes := common.Must(os.ReadFile("/home/g3po/Projects/advent_of_code_2024/inputs/05.txt"))
|
||||
result1, result2 := day05.Handle(bytes)
|
||||
fmt.Println(result1)
|
||||
fmt.Println(result2)
|
||||
}
|
||||
1367
inputs/05.txt
Normal file
1367
inputs/05.txt
Normal file
File diff suppressed because it is too large
Load Diff
79
internal/day05/handler.go
Normal file
79
internal/day05/handler.go
Normal file
@ -0,0 +1,79 @@
|
||||
package day05
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"aoc2024/internal/common"
|
||||
)
|
||||
|
||||
func Handle(input []byte) (int, int) {
|
||||
inputs := separateInput(input)
|
||||
rules := generateRules(inputs[0])
|
||||
lines := strings.Split(strings.TrimSpace(inputs[1]), "\n")
|
||||
result1, result2 := 0, 0
|
||||
|
||||
for _, line := range lines {
|
||||
checkRules(line, rules, &result1, &result2)
|
||||
}
|
||||
|
||||
return result1, result2
|
||||
}
|
||||
|
||||
func separateInput(input []byte) []string {
|
||||
re := regexp.MustCompile(`(?m)^\n*$`)
|
||||
result := re.Split(string(input), -1)
|
||||
result[0] = result[0][0 : len(result[0])-1]
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func generateRules(input string) map[int]map[int]struct{} {
|
||||
re := regexp.MustCompile(`\d*`)
|
||||
rules := map[int]map[int]struct{}{}
|
||||
lines := strings.Split(input, "\n")
|
||||
|
||||
for _, line := range lines {
|
||||
result := re.FindAllString(line, -1)
|
||||
n1 := common.StrToInt(result[0])
|
||||
n2 := common.StrToInt(result[1])
|
||||
|
||||
if _, ok := rules[n1]; !ok {
|
||||
rules[n1] = map[int]struct{}{n2: {}}
|
||||
} else {
|
||||
rules[n1][n2] = struct{}{}
|
||||
}
|
||||
|
||||
}
|
||||
return rules
|
||||
}
|
||||
|
||||
func checkRules(input string, rules map[int]map[int]struct{}, sum1, sum2 *int) {
|
||||
numbersStr := strings.Split(input, ",")
|
||||
number := make([]int, len(numbersStr))
|
||||
for i, str := range numbersStr {
|
||||
number[i] = common.StrToInt(str)
|
||||
}
|
||||
|
||||
for i, n := range number {
|
||||
for _, v := range number[:i+1] {
|
||||
if _, ok := rules[n][v]; ok {
|
||||
*sum2 += sortNumbers(number, rules)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
*sum1 += number[len(number)/2]
|
||||
}
|
||||
|
||||
func sortNumbers(n []int, rules map[int]map[int]struct{}) int {
|
||||
sort.Slice(n, func(i, j int) bool {
|
||||
_, ok := rules[n[i]][n[j]]
|
||||
return ok
|
||||
})
|
||||
|
||||
// fmt.Println(n)
|
||||
return n[len(n)/2]
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user