day 2, double awk

This commit is contained in:
setop 2024-12-02 09:15:41 +01:00
parent 7382d1a9d8
commit b68f57c83c
3 changed files with 56 additions and 0 deletions

14
d02/combine.awk Normal file
View File

@ -0,0 +1,14 @@
# emit a report and its variants as a bloc, separated by empty line
{
print
for (i=1;i<=NF;i++) {
r = ""
for (j=1;j<=NF;j++) {
if (i!=j) {
r = r $j " "
}
}
print r
}
print ""
}

17
d02/part1.awk Normal file
View File

@ -0,0 +1,17 @@
{
p = ($2 -$1) < 0 ? -1 : 1
safe = 1
for (i=2;i<=NF;i++) {
d = ($i - $(i-1))
q = d < 0 ? -1 : 1
if (p != q || d>3 || d<-3 || d == 0) {
safe = 0
break
}
}
#print NR, $0 , p, safe
S += safe
}
END {
print S
}

25
d02/part2.awk Normal file
View File

@ -0,0 +1,25 @@
# run with awk -f combine.awk < input | awk -f part2.awk
length == 0 {
#print "onesafe", onesafe
S+= onesafe>0 # if at least one variant is safe, then report is safe
onesafe = 0
next
}
{
p = ($2 -$1) < 0 ? -1 : 1 # uphill or downhill
safe = 1
for (i=2;i<=NF;i++) {
d = ($i - $(i-1))
q = d < 0 ? -1 : 1
if (q != p || d>3 || d<-3 || d == 0) {
safe = 0
break
}
}
#print NR, $0 , p, safe
onesafe += safe
}
END {
print S
}