2024 day1
This commit is contained in:
54
2024/go/day01/day01.go
Normal file
54
2024/go/day01/day01.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package day01
|
||||
|
||||
import (
|
||||
"adventofcode2024/utils"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func Part1(input string) int {
|
||||
var list1, list2 []int
|
||||
|
||||
num := 0
|
||||
lines := strings.Split(input, "\n")
|
||||
for _, line := range lines {
|
||||
fields := strings.Fields(line)
|
||||
// Convert the fields to integers
|
||||
val1 := utils.MustAtoi(fields[0])
|
||||
val2 := utils.MustAtoi(fields[1])
|
||||
|
||||
// Append to the respective slices
|
||||
list1 = append(list1, val1)
|
||||
list2 = append(list2, val2)
|
||||
}
|
||||
sort.Ints(list1)
|
||||
sort.Ints(list2)
|
||||
for i := 0; i < len(list1); i++ {
|
||||
num += utils.Abs(list1[i] - list2[i])
|
||||
}
|
||||
return num
|
||||
|
||||
}
|
||||
|
||||
func Part2(input string) int {
|
||||
var list1 []int
|
||||
list2 := make(map[int]int)
|
||||
|
||||
|
||||
num := 0
|
||||
lines := strings.Split(input, "\n")
|
||||
for _, line := range lines {
|
||||
fields := strings.Fields(line)
|
||||
// Convert the fields to integers
|
||||
val1 := utils.MustAtoi(fields[0])
|
||||
val2 := utils.MustAtoi(fields[1])
|
||||
|
||||
// Append to the respective slices
|
||||
list1 = append(list1, val1)
|
||||
list2[val2]++
|
||||
}
|
||||
for i := 0; i < len(list1); i++ {
|
||||
num += list1[i] * list2[list1[i]]
|
||||
}
|
||||
return num
|
||||
}
|
||||
17
2024/go/day01/day01_test.go
Normal file
17
2024/go/day01/day01_test.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package day01
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestPart1(t *testing.T) {
|
||||
r := Part1("")
|
||||
require.Equal(t, 0, r)
|
||||
}
|
||||
|
||||
func TestPart2(t *testing.T) {
|
||||
r := Part2("")
|
||||
require.Equal(t, 0, r)
|
||||
}
|
||||
1000
2024/go/day01/input.txt
Normal file
1000
2024/go/day01/input.txt
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user