Posted to tcl by schelte at Sat Dec 03 23:16:04 GMT 2022view raw

  1. #!/usr/bin/tclsh
  2.  
  3. proc prio {ch} {
  4. set p [scan $ch "%c"]
  5. return [expr {$p > 96 ? $p - 96 : $p - 64 + 26}]
  6. }
  7.  
  8. set input [read stdin]
  9.  
  10. set t0 0
  11. set t1 0
  12. foreach line [split $input "\n"] {
  13. set items [split $line {}]
  14. set n [expr {[llength $items] / 2}]
  15. foreach ch [lrange $items 0 [expr {$n - 1}]] {
  16. if {[lsearch -exact -start $n $items $ch] >= 0} {
  17. incr t0 [prio $ch]
  18. break
  19. }
  20. }
  21. foreach ch [lsort -unique $items] {
  22. dict incr count $ch
  23. }
  24. if {([incr linenum] % 3) == 0} {
  25. foreach ch [dict keys [dict filter $count value 3]] {
  26. incr t1 [prio $ch]
  27. }
  28. set count {}
  29. }
  30. }
  31.  
  32. puts "part1: $t0"
  33. puts "part2: $t1"
  34.