2016-day15: simple linear equation for position alignments

This commit is contained in:
alexchao26
2020-12-23 23:01:27 -05:00
parent 883f71fda3
commit f78cd9fb07
2 changed files with 98 additions and 0 deletions
+68
View File
@@ -0,0 +1,68 @@
package main
import (
"flag"
"fmt"
"strings"
"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)
ans := timingIsEverything(util.ReadFile("./input.txt"), part)
fmt.Println("Output:", ans)
}
func timingIsEverything(input string, part int) int {
discs := parseInput(input)
if part == 2 {
discs = append(discs, &disc{
number: len(discs) + 1,
positions: 11,
starting: 0,
})
}
t := 0
for {
var capsuleCollides bool
for _, d := range discs {
// some math equation for position must equal zero for the capsule to pass through each disc
timeSinceDrop := d.number
position := d.starting + t + timeSinceDrop
position %= d.positions
if position != 0 {
capsuleCollides = true
}
}
if !capsuleCollides {
break
}
t++
}
return t
}
type disc struct {
number int
positions int
starting int
}
func parseInput(input string) []*disc {
var discs []*disc
for _, l := range strings.Split(input, "\n") {
d := disc{}
fmt.Sscanf(l, "Disc #%d has %d positions; at time=0, it is at position %d.",
&d.number, &d.positions, &d.starting)
discs = append(discs, &d)
}
return discs
}
+30
View File
@@ -0,0 +1,30 @@
package main
import (
"testing"
"github.com/alexchao26/advent-of-code-go/util"
)
var example = `Disc #1 has 5 positions; at time=0, it is at position 4.
Disc #2 has 2 positions; at time=0, it is at position 1.`
func Test_timingIsEverything(t *testing.T) {
tests := []struct {
name string
input string
part int
want int
}{
{"example", example, 1, 5},
{"actual", util.ReadFile("input.txt"), 1, 317371},
{"actual", util.ReadFile("input.txt"), 2, 2080951},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := timingIsEverything(tt.input, tt.part); got != tt.want {
t.Errorf("timingIsEverything() = %v, want %v", got, tt.want)
}
})
}
}