Compare commits

..

4 Commits

Author SHA1 Message Date
3f795a451d test: add unit tests 2025-11-24 21:35:28 +01:00
c56c2aa449 feat: add main code 2025-11-24 21:35:22 +01:00
19ea2cd1f6 feat: add input 2025-11-24 21:35:19 +01:00
8594cd44d3 go: init 2021/day02 package 2025-11-24 21:35:14 +01:00
4 changed files with 1096 additions and 0 deletions

3
2021/day02/go.mod Normal file
View File

@@ -0,0 +1,3 @@
module 2021/day02
go 1.25.4

1000
2021/day02/input.txt Normal file

File diff suppressed because it is too large Load Diff

65
2021/day02/main.go Normal file
View File

@@ -0,0 +1,65 @@
package main
import (
"fmt"
"log"
"os"
"strconv"
"strings"
)
func parseInput(file string) []string {
content, err := os.ReadFile(file)
if err != nil {
log.Fatalf("Failed to read input file: %v", err)
}
return strings.Split(string(content), "\n")
}
func PartOne(data []string) int {
horizontal := 0
depth := 0
for _, line := range data {
parts := strings.Split(line, " ")
direction := parts[0]
amount, _ := strconv.Atoi(parts[1])
switch direction {
case "forward":
horizontal += amount
case "down":
depth += amount
case "up":
depth -= amount
}
}
return horizontal * depth
}
func PartTwo(data []string) int {
horizontal := 0
depth := 0
aim := 0
for _, line := range data {
parts := strings.Split(line, " ")
direction := parts[0]
amount, _ := strconv.Atoi(parts[1])
switch direction {
case "forward":
horizontal += amount
depth += aim * amount
case "down":
aim += amount
case "up":
aim -= amount
}
}
return horizontal * depth
}
func main() {
data := parseInput("input.txt")
fmt.Println("Part 1:", PartOne(data))
fmt.Println("Part 2:", PartTwo(data))
}

28
2021/day02/main_test.go Normal file
View File

@@ -0,0 +1,28 @@
package main
import "testing"
var testInput = []string{
"forward 5",
"down 5",
"forward 8",
"up 3",
"down 8",
"forward 2",
}
func TestPartOne(t *testing.T) {
expected := 150
got := PartOne(testInput)
if got != expected {
t.Errorf("PartOne() = %d, want %d", got, expected)
}
}
func TestPartTwo(t *testing.T) {
expected := 900
got := PartTwo(testInput)
if got != expected {
t.Errorf("PartTwo() = %d, want %d", got, expected)
}
}