From 1c770538b7a3ed80543b3aa49a3257316f0af639 Mon Sep 17 00:00:00 2001 From: Andrew Ekstedt Date: Fri, 8 Dec 2023 06:50:01 +0000 Subject: [PATCH] day 8 part 2 solution --- day08/sample3.in | 10 +++++++++ day08/sol.tcl | 58 ++++++++++++++++++++++++++++++++++-------------- 2 files changed, 51 insertions(+), 17 deletions(-) create mode 100644 day08/sample3.in diff --git a/day08/sample3.in b/day08/sample3.in new file mode 100644 index 0000000..5b3fa58 --- /dev/null +++ b/day08/sample3.in @@ -0,0 +1,10 @@ +LR + +11A = (11B, XXX) +11B = (XXX, 11Z) +11Z = (11B, XXX) +22A = (22B, XXX) +22B = (22C, 22C) +22C = (22Z, 22Z) +22Z = (22B, 22B) +XXX = (XXX, XXX) diff --git a/day08/sol.tcl b/day08/sol.tcl index f9b9e50..ebf2042 100755 --- a/day08/sol.tcl +++ b/day08/sol.tcl @@ -41,28 +41,52 @@ proc ghost-solve {dirs graph} { } set end($node) [string match "*Z" $node] } - set node $start - set steps 0 puts "start: $node" - while {1} { - set done 1 - foreach n $node { - if {! $end($n)} { - set done 0 - break + set lengths {} + foreach node $start { + array set seen {} + set node0 $node + set path $node + set steps 0 + # we make a couple simplifying assumptions: + # first, that there is only one exit node on each cycle + # and two, that the exits do not line up before the first cycle + # + # find how long it takes to get to the exit the first time + # then find the first cycle + set initial -1 + set sanity -1 + set cycle {} + while {1} { + set i [expr {$steps % [llength $dirs]}] + if {$end($node)} { + if {$initial < 0} { + set initial $steps + set sanity $i + } else { + set cycle $steps + if {$i != $sanity} { error "exit cycle desync" } + break + } } + set d [expr {[lindex $dirs $i] eq "L" ? 0 : 1}] + set node [lindex $G($node) $d] + #lappend path $node + #puts "$d -> $node" + incr steps } - if {$done} break - - set d [lindex $dirs [expr {$steps % [llength $dirs]}]] - set i [expr {$d eq "L" ? 0 : 1}] - set node [lmap n $node {lindex $G($n) $i}] - #puts "$d -> $node" - incr steps + set len [expr {$cycle - $initial}] + puts "$node0: found cycle of $len steps after $initial steps at node $node" + # assumption #3: len == initial + lappend lengths $len } - puts "$steps" + + # i'm too tired to code up a LCM function in tcl + puts $lengths + puts [exec python -c "import numpy; print(numpy.lcm.reduce(\[[join $lengths ","]\]))"] + #puts "$steps" } set data [read-input stdin] -#solve {*}$data +solve {*}$data ghost-solve {*}$data