adventofcode2023/day09/sol.tcl

52 lines
994 B
Tcl
Executable File

#!/usr/bin/env tclsh
source ../prelude.tcl
proc diff {lst} {
set out {}
for {set i 1} {$i < [llength $lst]} {incr i} {
lappend out [expr {[lindex $lst $i] - [lindex $lst [expr {$i-1}]]}]
}
return $out
}
proc allzeros {lst} {
foreach x $lst {
if {$x != 0} { return 0 }
}
return 1
}
proc predict {lst} {
#puts "predict $lst"
if {[allzeros $lst]} {
return 0
}
return [expr {[lindex $lst end] + [predict [diff $lst]]}]
}
proc unpredict {lst} {
# note: this could be
# return [predict [lreverse $lst]]
if {[allzeros $lst]} {
return 0
}
return [expr {[lindex $lst 0] - [unpredict [diff $lst]]}]
}
proc solve input {
set fw {}
set bw {}
while {[gets $input line] >= 0} {
set next [predict $line]
set prev [unpredict $line]
lappend fw $next
lappend bw $prev
puts "$prev {$line} $next"
}
puts [ladd $fw]
puts [ladd $bw]
}
solve stdin