summaryrefslogtreecommitdiffstats
path: root/2024/tcl/05.tcl
diff options
context:
space:
mode:
Diffstat (limited to '2024/tcl/05.tcl')
-rwxr-xr-x2024/tcl/05.tcl68
1 files changed, 68 insertions, 0 deletions
diff --git a/2024/tcl/05.tcl b/2024/tcl/05.tcl
new file mode 100755
index 0000000..1ea1e4d
--- /dev/null
+++ b/2024/tcl/05.tcl
@@ -0,0 +1,68 @@
+#!/bin/env tclsh
+
+source lib.tcl
+setup 5
+
+puts {Part 1: Total of middle numbers of update sets matching rules}
+
+set rules {}
+set updates {}
+set dorules 1
+foreach line $input {
+ if {$line == {}} {set dorules 0; continue}
+ if $dorules {
+ lassign [split $line |] X Y
+ dict lappend rules $X $Y
+ } else {
+ lappend updates [split $line ,]
+ }
+}
+
+proc rulesorter {a b} {
+ global rules
+ if {[dict exists $rules $a] && [lsearch -exact [dict get $rules $a] $b] != -1} { return 1 }
+ if {[dict exists $rules $b] && [lsearch -exact [dict get $rules $b] $a] != -1} { return -1 }
+ return 0
+}
+
+#puts $rules
+#puts $updates
+
+set middle_total 0
+set bad_updates {}
+foreach update $updates {
+ set update1 [lassign $update seen]
+ set updateok 1
+ foreach page $update1 {
+ lappend seen $page
+ if ![dict exists $rules $page] continue
+# puts "[list $update]: $page, [dict get $rules $page], $seen"
+ foreach rule [dict get $rules $page] {
+ if {[lsearch -exact $seen $rule] != -1} {
+# puts $update\n$page\n$seen\n$rule
+ set updateok 0
+ break
+ }
+ }
+ if !$updateok break
+ }
+ if $updateok {
+# puts "adding [lindex $update [expr {[llength $update] / 2}]] [list $update]"
+ incr middle_total [lindex $update [expr {[llength $update] / 2}]]
+ } else {
+ lappend bad_updates $update
+ }
+}
+
+puts "Total of middle numbers: $middle_total"
+
+puts ""
+puts {Part 2: Total of middle numbers of sorted unordered sets}
+
+set bad_middle_total 0
+foreach update $bad_updates {
+ set update [lsort -command rulesorter $update]
+ incr bad_middle_total [lindex $update [expr {[llength $update] / 2}]]
+}
+
+puts "Total of middle numbers: $bad_middle_total"