diff --git a/go.work b/go.work index cd04e7c..9639f06 100644 --- a/go.work +++ b/go.work @@ -12,4 +12,5 @@ use ( ./solutions/year-2022/day-05 ./solutions/year-2022/day-06 ./solutions/year-2023/day-01 + ./solutions/year-2024/day-01 ) diff --git a/solutions/year-2024/day-01/go.mod b/solutions/year-2024/day-01/go.mod new file mode 100644 index 0000000..e9e2849 --- /dev/null +++ b/solutions/year-2024/day-01/go.mod @@ -0,0 +1,3 @@ +module github.com/atifcppprogrammer/advent-of-golang/solutions/year-2024/day-01 + +go 1.23.4 diff --git a/solutions/year-2024/day-01/main.go b/solutions/year-2024/day-01/main.go new file mode 100644 index 0000000..6a84b1f --- /dev/null +++ b/solutions/year-2024/day-01/main.go @@ -0,0 +1,68 @@ +package main + +import ( + "github.com/atifcppprogrammer/advent-of-golang/internal/utilities" + "sort" + "strconv" + "strings" +) + +func main() { + filepath := utilities.GetInputFile() + lines, _ := utilities.ReadLines(filepath) + + result := solution(lines) + utilities.PrintSolution("2024", 01, "", strconv.Itoa(result)) +} + +func solution(lines []string) (result int) { + var ( + count = len(lines) + l1 = make(sort.IntSlice, count) + l2 = make(sort.IntSlice, count) + ) + + for i, line := range lines { + val1, val2, _ := strings.Cut(line, " ") + num1, _ := strconv.Atoi(val1) + num2, _ := strconv.Atoi(val2) + l1[i] = num1 + l2[i] = num2 + } + + if utilities.SolutionPart == 1 { + sort.Sort(l1) + sort.Sort(l2) + + for i := 0; i < count; i++ { + diff := l1[i] - l2[i] + if diff < 0 { + result += -diff + } else { + result += +diff + } + } + + return + } + + if utilities.SolutionPart == 2 { + numCounts := make(map[int]int) + + for _, num := range l2 { + if _, exists := numCounts[num]; !exists { + numCounts[num] = 1 + } else { + numCounts[num]++ + } + } + + for _, num := range l1 { + if count, exists := numCounts[num]; exists { + result += num * count + } + } + } + + return +} diff --git a/solutions/year-2024/day-01/main_test.go b/solutions/year-2024/day-01/main_test.go new file mode 100644 index 0000000..151abc3 --- /dev/null +++ b/solutions/year-2024/day-01/main_test.go @@ -0,0 +1,43 @@ +package main + +import ( + "fmt" + "testing" + + "github.com/atifcppprogrammer/advent-of-golang/internal/utilities" +) + +func setSolutionPartEnv(t *testing.T, solutionPart string) { + t.Setenv("PART", solutionPart) + utilities.SetSolutionPart() +} + +func TestSolution(t *testing.T) { + t.Run("solves example input correctly", func(t *testing.T) { + lines := []string{ + "3 4", + "4 3", + "2 5", + "1 3", + "3 9", + "3 3", + } + + tests := []struct { + solutionPart string + want int + }{ + {solutionPart: "1", want: 11}, + {solutionPart: "2", want: 31}, + } + for _, tt := range tests { + t.Run(fmt.Sprintf("solves example correct for part %s", tt.solutionPart), func(t *testing.T) { + setSolutionPartEnv(t, tt.solutionPart) + got, want := solution(lines), tt.want + if got != want { + t.Errorf("want %d got %d", want, got) + } + }) + } + }) +}