adventofcode2022/day05/sol.awk

61 lines
1.4 KiB
Awk
Raw Normal View History

2022-12-07 08:05:58 +00:00
# run me with awk -f sol.awk < input
2022-12-07 20:07:43 +00:00
/\[/ { # " [A] [B] [C] "
gsub("^ ", "[ ]") # "[ ] [A] [B] [C] "
gsub(" {4}", " [ ]") # "[ ] [A] [ ] [B] [C] [ ]"
gsub("^\\[|\\] \\[|\\]$", "") # " A BC "
2022-12-07 08:05:58 +00:00
lines[nlines++] = $0
if (nstacks < length())
nstacks = length()
}
/^$/ {
2022-12-07 20:07:43 +00:00
# transpose lines[j][i] -> stack[i][-j]
# and strip trailing spaces
2022-12-07 08:05:58 +00:00
for (i = 1; i <= nstacks; i++) {
s = ""
for (j = nlines-1; j >= 0; j--) {
c = substr(lines[j], i, 1)
if (c != " ") s = s c
}
stack[i] = s
stack2[i] = s
print s "."
}
print "----"
}
function reverse(s) {
r = ""
for (i = length(s); i > 0; i--)
r = r substr(s, i, 1)
return r
}
function move(S, n, fr, to, flip) {
#print n, fr, to
m = length(S[fr]) - n
if (flip) chunk = reverse(substr(S[fr], m+1))
else chunk = substr(S[fr], m+1)
#print stack[to]
#print stack[fr]
S[to] = S[to] chunk
S[fr] = substr(S[fr], 1, m)
#print stack[to]
#print stack[fr]
}
/^move .* from .* to .*/ {
2022-12-07 20:17:58 +00:00
move(stack, $2, $4, $6, 1)
move(stack2, $2, $4, $6, 0)
2022-12-07 08:05:58 +00:00
}
END {
for (i = 1; i <= nstacks; i++) {
p1 = p1 substr(stack[i], length(stack[i]))
p2 = p2 substr(stack2[i], length(stack2[i]))
}
print p1
print p2
}