1
Fork 0
Browse Source

Day 02

master
Jan-Lukas Else 7 months ago
parent
commit
0d8a41e58c
  1. 1000
      02/input.txt
  2. 66
      02/main.go
  3. 14
      02/main_test.go

1000
02/input.txt

File diff suppressed because it is too large Load Diff

66
02/main.go

@ -0,0 +1,66 @@
package main
import (
"log"
"os"
"strconv"
"strings"
)
func main() {
inputBytes, _ := os.ReadFile("input.txt")
inputs := strings.Split(string(inputBytes), "\n")
log.Println("Puzzle 1:", puzzle1(inputs))
log.Println("Puzzle 2:", puzzle2(inputs))
}
func puzzle1(input []string) int {
// "forward X" increases the horizontal position by X units.
// "down X" increases the depth by X units.
// "up X" decreases the depth by X units.
horizontal := 0
depth := 0
for _, instruction := range input {
instructionParts := strings.Split(instruction, " ")
direction := instructionParts[0]
distance, _ := strconv.Atoi(instructionParts[1])
switch direction {
case "forward":
horizontal += distance
case "down":
depth += distance
case "up":
depth -= distance
}
}
// Multiply horizontal position and depth together to get the final answer.
return horizontal * depth
}
func puzzle2(input []string) int {
// down X increases your aim by X units.
// up X decreases your aim by X units.
// forward X does two things:
// - It increases your horizontal position by X units.
// - It increases your depth by your aim multiplied by X.
horizontal := 0
depth := 0
aim := 0
for _, instruction := range input {
instructionParts := strings.Split(instruction, " ")
direction := instructionParts[0]
distance, _ := strconv.Atoi(instructionParts[1])
switch direction {
case "down":
aim += distance
case "up":
aim -= distance
case "forward":
horizontal += distance
depth += aim * distance
}
}
// Multiply horizontal position and depth together to get the final answer.
return horizontal * depth
}

14
02/main_test.go

@ -0,0 +1,14 @@
package main
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func Test(t *testing.T) {
input := `forward 5,down 5,forward 8,up 3,down 8,forward 2`
assert.Equal(t, 150, puzzle1(strings.Split(input, ",")))
assert.Equal(t, 900, puzzle2(strings.Split(input, ",")))
}
Loading…
Cancel
Save