Compare commits
4 Commits
f8d8916b60
...
3f795a451d
| Author | SHA1 | Date | |
|---|---|---|---|
| 3f795a451d | |||
| c56c2aa449 | |||
| 19ea2cd1f6 | |||
| 8594cd44d3 |
3
2021/day02/go.mod
Normal file
3
2021/day02/go.mod
Normal file
@@ -0,0 +1,3 @@
|
||||
module 2021/day02
|
||||
|
||||
go 1.25.4
|
||||
1000
2021/day02/input.txt
Normal file
1000
2021/day02/input.txt
Normal file
File diff suppressed because it is too large
Load Diff
65
2021/day02/main.go
Normal file
65
2021/day02/main.go
Normal 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
28
2021/day02/main_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user