diff options
| author | Mistivia <i@mistivia.com> | 2024-12-21 17:43:33 +0800 |
|---|---|---|
| committer | Mistivia <i@mistivia.com> | 2024-12-21 17:43:33 +0800 |
| commit | 5267ea3f9a9ba1f0555f36e7d11b72843f7d523e (patch) | |
| tree | 699a1cffc39b08cd2cbfcdcd67d8f5c1bcc3fdde /07 | |
| parent | 211677cbbfd0e0d4015bea07d84cd37834c5a5d1 (diff) | |
day 7 part 2
Diffstat (limited to '07')
| -rw-r--r-- | 07/2.tcl | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/07/2.tcl b/07/2.tcl new file mode 100644 index 0000000..af6bd65 --- /dev/null +++ b/07/2.tcl @@ -0,0 +1,31 @@ +set fp [open "input"] +set equations {} +while {[gets $fp line] >= 0} { + set s1 [split $line ":"] + lappend equations $s1 +} + +proc can_match_impl {target numbers current} { + if {0 == [llength $numbers]} { + return [expr {$target == $current}] + } + set rest [lrange $numbers 1 end] + set first [lindex $numbers 0] + return [expr {[can_match_impl $target $rest [expr {$current * $first}]] + || [can_match_impl $target $rest [expr {$current + $first}]] + || [can_match_impl $target $rest "$current$first"]}] +} + +proc can_match {target numbers} { + return [can_match_impl $target [lrange $numbers 1 end] [lindex $numbers 0]] +} + +set sum 0 +foreach elem $equations { + set test_value [lindex $elem 0] + set numbers [lindex $elem 1] + if {[can_match $test_value $numbers]} { + set sum [expr {$sum + $test_value}] + } +} +puts $sum |
