From 92dd4115528a495a2acf3958de52d5511fc3108a Mon Sep 17 00:00:00 2001 From: Aleteoryx Date: Sat, 7 Dec 2024 12:33:09 -0500 Subject: 2024.05, 2 days late --- 2024/tcl/05.tcl | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100755 2024/tcl/05.tcl (limited to '2024/tcl/05.tcl') 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" -- cgit v1.2.3-70-g09d2