adventofcode2023/day06/sol.tcl

37 lines
1.2 KiB
Tcl
Executable File

#!/usr/bin/env tclsh
package require Tcl 8.6
set input stdin
regexp {Time: (.*)} [gets $input] _ time
regexp {Distance: (.*)} [gets $input] _ dist
proc solve {t d} {
# the distance traveled if the boat is released at time i
# is equal to (t-i)*i
# we want to know the range of values of i for which this
# exceeds the best time (d)
# (t-i)*i > d
# a little rearranging gets us the quadratic equation
# i^2 - ti + d <= 0
# which we can determine the crossing points for
# using the quadratic formula (the good one, not the
# one you learned in school)
#puts "solve $t $d"
set h [expr {$t / 2.0}]
set s [expr {sqrt($h*$h - $d)}]
set a [expr {int($h-$s)}]
set b [expr {int($h+$s)}]
# in general these will not be at integer values,
# so we probe the floor and ceiling of each crossing
# point to determine exactly where the condition is met
if {($t-$a)*$a <= $d} { incr a }
if {($t-$b)*$b > $d} { incr b }
#puts "a=$a b=$b"
return [expr {$b - $a}]
}
proc lmul {list} { return [expr [join $list *]] }
proc smush {list} { return [join $list ""] }
puts "Part 1: [lmul [lmap t $time d $dist {solve $t $d}]]"
puts "Part 2: [solve [smush $time] [smush $dist]]"