2023 day 08 properly

This commit is contained in:
tristan 2023-12-09 15:51:37 +00:00
parent 9b5de2f13e
commit bfcad28fff
2 changed files with 8 additions and 18 deletions

View file

@ -14,7 +14,7 @@ func StepsToSolveAll(ins string, net Network) (int, error) {
current := GetStarts(net) current := GetStarts(net)
res := 1 res := 1
for _,start := range current { for _,start := range current {
_, steps, err := StepsToSolve(ins, net, start) steps, err := StepsToSolve(ins, net, start)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@ -43,10 +43,9 @@ func IsDone(state []string) bool {
return true return true
} }
func StepsToSolve(ins string, net Network, start string) (int, int, error) { func StepsToSolve(ins string, net Network, start string) (int, error) {
current := start current := start
steps := 0; steps := 0;
history := []string{current}
for { for {
switch ins[steps % len(ins)] { switch ins[steps % len(ins)] {
case 'L': case 'L':
@ -54,15 +53,12 @@ func StepsToSolve(ins string, net Network, start string) (int, int, error) {
case 'R': case 'R':
current = net[current][1] current = net[current][1]
default: default:
return 0, 0, fmt.Errorf("instructions unclear! Must only be 'R' and 'L', but got '%c' at [%v]", ins[steps], steps) return 0, fmt.Errorf("instructions unclear! Must only be 'R' and 'L', but got '%c' at [%v]", ins[steps], steps)
} }
steps ++ steps ++
for step, state := range history { if current[2] == goal {
if state == current && step == steps % len(ins) { return steps, nil
return step, steps-step, nil
}
} }
history = append(history, current)
} }
} }

View file

@ -55,18 +55,12 @@ func TestStepsToSolve(t *testing.T) {
"22Z": [2]string{"22B", "22B"}, "22Z": [2]string{"22B", "22B"},
"XXX": [2]string{"XXX", "XXX"}, "XXX": [2]string{"XXX", "XXX"},
} }
start, steps, err := StepsToSolve("RL", net, "11B") steps, err := StepsToSolve("LR", net, "11A")
equal(t, err, nil) equal(t, err, nil)
equal(t, start, 0)
equal(t, steps, 2) equal(t, steps, 2)
start, steps, err = StepsToSolve("LR", net, "11A") steps, err = StepsToSolve("LR", net, "22A")
equal(t, err, nil) equal(t, err, nil)
equal(t, start, 1) equal(t, steps, 3)
equal(t, steps, 2)
start, steps, err = StepsToSolve("LR", net, "22A")
equal(t, err, nil)
equal(t, start, 1)
equal(t, steps, 6)
} }
func TestLCM(t *testing.T) { func TestLCM(t *testing.T) {