2.tcl 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. set fp [open "input"]
  2. gets $fp line
  3. close $fp
  4. proc is_even {x} {
  5. return [expr {$x % 2 == 0}]
  6. }
  7. proc zero_trim {x} {
  8. for {set i 0} {$i < [expr {[string length $x] - 1}]} {incr i} {
  9. if {[string index $x $i] != 0} {
  10. break
  11. }
  12. }
  13. return [string range $x $i end]
  14. }
  15. set blinked_length_cache {}
  16. proc blinked_length {x n} {
  17. global blinked_length_cache
  18. if {$n == 0} {
  19. return 1
  20. }
  21. set key "$x,$n"
  22. if {[dict exists $blinked_length_cache $key]} {
  23. return [dict get $blinked_length_cache $key]
  24. }
  25. if {$x == 0} {
  26. set result [blinked_length 1 [expr {$n - 1}]]
  27. dict set blinked_length_cache $key $result
  28. return $result
  29. }
  30. if {[is_even [string length $x]]} {
  31. set len [string length $x]
  32. set halflen [expr {$len / 2}]
  33. set first [zero_trim [string range $x 0 [expr {$halflen - 1}]]]
  34. set second [zero_trim [string range $x $halflen end]]
  35. set next_n [expr {$n - 1}]
  36. set result [expr {[blinked_length $first $next_n] \
  37. + [blinked_length $second $next_n]}]
  38. dict set blinked_length_cache $key $result
  39. return $result
  40. }
  41. set result [blinked_length [expr {$x * 2024}] [expr {$n - 1}]]
  42. dict set blinked_length_cache $key $result
  43. return $result
  44. }
  45. set lst $line
  46. set sum 0
  47. foreach x $lst {
  48. incr sum [blinked_length $x 75]
  49. }
  50. puts $sum