#!/bin/env tclsh source lib.tcl setup 2 puts {Part 1: Count "safe" ordered sequences with intervals such that 1 <= x <= 3.} proc row_errs {row} { set report [lassign $row first second] set neg [expr {abs($second - $first) != ($second - $first)}] set prev $first set row_errs 0 foreach num [concat $second $report] { if {$neg != (abs($num - $prev) != ($num - $prev)) || abs($num - $prev) > 3 || abs($num - $prev) < 1} { incr row_errs } else { set prev $num } } return $row_errs } while {[gets $input report] != -1} { if ![row_errs $report] { incr safe_count; continue } # naive, but handles a case like [1 4 2 3] where removing 2 makes it # safe but an iterative approach only trips on [2]. backtracking # might be better but idc for {set i 0} {$i < [llength $report]} {incr i} { if ![row_errs [lreplace $report $i $i]] { incr dampened_safe_count break } } } incr dampened_safe_count $safe_count close $input puts "Safe sequence count: $safe_count" puts "" puts {Part 2: Tolerate 1 bad entry in a report.} puts "Dampened sequence count: $dampened_safe_count"