summaryrefslogtreecommitdiffstats
path: root/2024/tcl/07.tcl
blob: 9cc9ddd1a19dcb164aa319184a627e901cfb30b4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/bin/env tclsh

source lib.tcl
setup 7

puts {Part 1: Total of valid test lines}

proc op_search {targ cur rest} {
  set rest [lassign $rest next]
  if {$rest == {}} {
    expr {$cur + $next == $targ || $cur * $next == $targ}
  } else {
    expr {[op_search $targ [expr {$cur + $next}] $rest] ||
          [op_search $targ [expr {$cur * $next}] $rest]}
  }
}
proc op_search_cat {targ cur rest} {
  set rest [lassign $rest next]
  if {$rest == {}} {
#    puts "leaf: $cur,$next // $targ"
    expr {$cur + $next == $targ || $cur * $next == $targ || [string cat $cur $next] == $targ}
  } else {
#    puts "branch: $cur,$next .. $rest // $targ"
    expr {[op_search_cat $targ [expr {$cur + $next}] $rest] ||
          [op_search_cat $targ [expr {$cur * $next}] $rest] ||
          [op_search_cat $targ [string cat $cur $next] $rest]}
  }
}

set test_total 0
set cat_test_total 0
foreach line $input {
  lassign [split $line :] targ nums
  set nums [lassign $nums first]
  if [op_search $targ $first $nums] {
    incr test_total $targ
  }
  if [op_search_cat $targ $first $nums] {
    incr cat_test_total $targ
  }
}

puts "Total: $test_total"

puts ""
puts {Part 2: Total of valid test lines with || operator}

puts "Total: $cat_test_total"