1.tcl 821 B

123456789101112131415161718192021222324252627282930
  1. set fp [open "input"]
  2. set equations {}
  3. while {[gets $fp line] >= 0} {
  4. set s1 [split $line ":"]
  5. lappend equations $s1
  6. }
  7. proc can_match_impl {target numbers current} {
  8. if {0 == [llength $numbers]} {
  9. return [expr {$target == $current}]
  10. }
  11. set rest [lrange $numbers 1 end]
  12. set first [lindex $numbers 0]
  13. return [expr {[can_match_impl $target $rest [expr {$current * $first}]]
  14. || [can_match_impl $target $rest [expr {$current + $first}]]}]
  15. }
  16. proc can_match {target numbers} {
  17. return [can_match_impl $target [lrange $numbers 1 end] [lindex $numbers 0]]
  18. }
  19. set sum 0
  20. foreach elem $equations {
  21. set test_value [lindex $elem 0]
  22. set numbers [lindex $elem 1]
  23. if {[can_match $test_value $numbers]} {
  24. set sum [expr {$sum + $test_value}]
  25. }
  26. }
  27. puts $sum