From 29b20e27fc3b78c536b0e7764ba7dbf677530134 Mon Sep 17 00:00:00 2001 From: Andrew Ekstedt Date: Wed, 7 Dec 2022 00:05:58 -0800 Subject: [PATCH] day 5 awk solution --- day05/sol.awk | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 day05/sol.awk diff --git a/day05/sol.awk b/day05/sol.awk new file mode 100644 index 0000000..7beb429 --- /dev/null +++ b/day05/sol.awk @@ -0,0 +1,58 @@ +# run me with awk -f sol.awk < input + +/\[/ { + gsub("^ ", "[ ]") + gsub(" {4}", " [ ]") + gsub("^\\[|\\] \\[|\\]$", "") + lines[nlines++] = $0 + if (nstacks < length()) + nstacks = length() +} + +/^$/ { + 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 .*/ { + move(stack, $2, $4, $6, 0) + move(stack2, $2, $4, $6, 1) +} + +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 +}