mirror of
https://github.com/Threnklyn/advent-of-code-go.git
synced 2026-06-07 20:53:30 +02:00
2015-day02: simple geometry calcs
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/alexchao26/advent-of-code-go/mathutil"
|
||||
"github.com/alexchao26/advent-of-code-go/util"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var part int
|
||||
flag.IntVar(&part, "part", 1, "part 1 or 2")
|
||||
flag.Parse()
|
||||
fmt.Println("Running part", part)
|
||||
|
||||
var ans int
|
||||
if part == 1 {
|
||||
ans = part1(util.ReadFile("./input.txt"))
|
||||
} else {
|
||||
ans = part2(util.ReadFile("./input.txt"))
|
||||
}
|
||||
fmt.Println("Output:", ans)
|
||||
}
|
||||
|
||||
func part1(input string) int {
|
||||
var totalSqFt int
|
||||
for _, line := range strings.Split(input, "\n") {
|
||||
var x, y, z int
|
||||
_, err := fmt.Sscanf(line, "%dx%dx%d", &x, &y, &z)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
totalSqFt += x * y * 2
|
||||
totalSqFt += x * z * 2
|
||||
totalSqFt += z * y * 2
|
||||
totalSqFt += mathutil.MinInt(x*y, y*z, x*z) // slack in wrapping paper...
|
||||
}
|
||||
|
||||
return totalSqFt
|
||||
}
|
||||
|
||||
func part2(input string) int {
|
||||
var totalLen int
|
||||
for _, line := range strings.Split(input, "\n") {
|
||||
var x, y, z int
|
||||
_, err := fmt.Sscanf(line, "%dx%dx%d", &x, &y, &z)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
cubic := x * y * z
|
||||
totalLen += cubic
|
||||
sides := []int{
|
||||
2 * (x + y),
|
||||
2 * (y + z),
|
||||
2 * (x + z),
|
||||
}
|
||||
totalLen += mathutil.MinInt(sides...)
|
||||
}
|
||||
return totalLen
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/alexchao26/advent-of-code-go/util"
|
||||
)
|
||||
|
||||
var example = `2x3x4
|
||||
1x1x10`
|
||||
|
||||
func Test_part1(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
want int
|
||||
}{
|
||||
{"example", example, 58 + 43},
|
||||
{"actual", util.ReadFile("input.txt"), 1588178},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := part1(tt.input); got != tt.want {
|
||||
t.Errorf("part1() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_part2(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
want int
|
||||
}{
|
||||
{"actual", util.ReadFile("input.txt"), 3783758},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := part2(tt.input); got != tt.want {
|
||||
t.Errorf("part2() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user