day 8 part 2 solution

main
magical 2023-12-08 06:50:01 +00:00
parent 792c9b5e23
commit 1c770538b7
2 changed files with 51 additions and 17 deletions

10
day08/sample3.in 100644
View File

@ -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)

View File

@ -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