adventofcode2023/day09/sol.tcl

52 lines
994 B
Tcl
Raw Normal View History

2023-12-09 05:27:36 +00:00
#!/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} {
2023-12-09 07:15:58 +00:00
# note: this could be
# return [predict [lreverse $lst]]
2023-12-09 05:27:36 +00:00
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