mirror of
https://github.com/Threnklyn/advent-of-code-go.git
synced 2026-05-18 19:13:27 +02:00
day 2, knocking off rust still
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"flag"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/alexchao26/advent-of-code-go/cast"
|
||||
"github.com/alexchao26/advent-of-code-go/util"
|
||||
)
|
||||
|
||||
//go:embed input.txt
|
||||
var input string
|
||||
|
||||
func init() {
|
||||
// do this in init (not main) so test file has same input
|
||||
input = strings.TrimRight(input, "\n")
|
||||
if len(input) == 0 {
|
||||
panic("empty input.txt file")
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
var part int
|
||||
flag.IntVar(&part, "part", 1, "part 1 or 2")
|
||||
flag.Parse()
|
||||
fmt.Println("Running part", part)
|
||||
|
||||
ans := day2(input, part)
|
||||
util.CopyToClipboard(fmt.Sprintf("%v", ans))
|
||||
fmt.Println("Output:", ans)
|
||||
}
|
||||
|
||||
func day2(input string, part int) int {
|
||||
var horiz, depth int
|
||||
var aim int
|
||||
|
||||
for _, line := range strings.Split(input, "\n") {
|
||||
parts := strings.Split(line, " ")
|
||||
dir := parts[0]
|
||||
dist := cast.ToInt(parts[1])
|
||||
|
||||
if part == 1 {
|
||||
switch dir {
|
||||
case "down":
|
||||
depth += dist
|
||||
case "up":
|
||||
depth -= dist
|
||||
case "forward":
|
||||
horiz += dist
|
||||
}
|
||||
} else {
|
||||
switch dir {
|
||||
case "down":
|
||||
aim += dist
|
||||
case "up":
|
||||
aim -= dist
|
||||
case "forward":
|
||||
horiz += dist
|
||||
depth += aim * dist
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return horiz * depth
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
var example = `forward 5
|
||||
down 5
|
||||
forward 8
|
||||
up 3
|
||||
down 8
|
||||
forward 2`
|
||||
|
||||
func Test_day2(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
part int
|
||||
want int
|
||||
}{
|
||||
{
|
||||
name: "example",
|
||||
input: example,
|
||||
part: 1,
|
||||
want: 150,
|
||||
},
|
||||
{
|
||||
name: "actual",
|
||||
input: input,
|
||||
part: 1,
|
||||
want: 1813801,
|
||||
},
|
||||
{
|
||||
name: "example",
|
||||
input: example,
|
||||
part: 2,
|
||||
want: 900,
|
||||
},
|
||||
{
|
||||
name: "actual",
|
||||
input: input,
|
||||
part: 2,
|
||||
want: 1960569556,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := day2(tt.input, tt.part); got != tt.want {
|
||||
t.Errorf("part1() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user