adventofcode2023/prelude.tcl

59 lines
1.2 KiB
Tcl

package require Tcl 8.6
namespace import tcl::mathfunc::min
namespace import tcl::mathfunc::max
proc {#} args {}
# short aliases for common things
proc llen {lst} { return [llength $lst] }
proc slen {str} { return [string length $str] }
proc trim args { return [uplevel [concat string trim $args]] }
proc replace {str a b} { return [string map [list $a $b] $str] }
# sum and product
proc ladd {list} {
set t 0
foreach x $list { incr t $x }
return $t
}
proc lmul {list} {
set p 1
foreach x $list { set p [expr {$p * $x}] }
return $p
}
# split s on a substring
proc splitstr {s sep} {
# replace $sep with ascii char 30, aka "record separator"
return [split [replace $s $sep "\x1E"] "\x1E"]
}
proc must_regexp args {
if {! [uplevel [concat regexp $args]]} {
error "regexp failed"
}
}
# transpose a list of strings
#
# % transpose {abc 123}
# a1 b2 c3
# % transpose a1 b2 c3
# abc 123
#
proc transpose strings {
set out {}
set C [slen [lindex $strings 0]]
for {set i 0} {$i < $C} {incr i} {
set column {}
foreach row $strings {
lappend column [string index $row $i]
}
lappend out [join $column ""]
}
return $out
}