day 6 tcl solution
parent
ed146f7fe1
commit
905dee030f
|
@ -0,0 +1,43 @@
|
||||||
|
#!/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 product {list} {
|
||||||
|
set p 1
|
||||||
|
foreach x $list {
|
||||||
|
set p [expr {$p * $x}]
|
||||||
|
}
|
||||||
|
return $p
|
||||||
|
}
|
||||||
|
|
||||||
|
proc smush {x} { return [join $x ""] }
|
||||||
|
|
||||||
|
puts "Part 1: [product [lmap t $time d $dist {solve $t $d}]]"
|
||||||
|
puts "Part 2: [solve [smush $time] [smush $dist]]"
|
Loading…
Reference in New Issue