Advertisement
SadBunny

AOC 2022 Day 5 parts 1+2 (AWK)

Dec 5th, 2022
1,552
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Awk 1.68 KB | Source Code | 0 0
  1. {
  2.         if ($0 == "" || $0 ~ " 1   ") { go = 1; next; }
  3.  
  4.         if (!go) {
  5.                 # We are still reading the initial stacks.
  6.                 for (i=1; i<=9; i++) {
  7.                         letter = substr($0, i*4-2, 1);
  8.                         # Read in reverse due do weird input format
  9.                         string_part1[i] = (letter != " " ? substr($0, i*4-2, 1) : "") string_part1[i];
  10.                         string_part2[i] = (letter != " " ? substr($0, i*4-2, 1) : "") string_part2[i];
  11.                 }
  12.                 next;
  13.         }
  14.  
  15.         # If we get here, we are reading the actual crate moving instructions.
  16.  
  17.         split($0, op, " ");
  18.  
  19.         count = op[2];
  20.         from = op[4];
  21.         to = op[6];
  22.  
  23.         # Use next line for part 1:
  24.         string_part1[to] = string_part1[to] reverse(substr(string_part1[from], length(string_part1[from]) - count + 1));
  25.         string_part2[to] = string_part2[to]         substr(string_part2[from], length(string_part2[from]) - count + 1);
  26.  
  27.         string_part1[from] = substr(string_part1[from], 1, length(string_part1[from]) - count);
  28.         string_part2[from] = substr(string_part2[from], 1, length(string_part2[from]) - count);
  29. }
  30.  
  31. END {
  32.         printf "Part 1: "
  33.         for (i in string_part1) {
  34.                 printf substr(string_part1[i], length(string_part1[i]), 1);
  35.         }
  36.         printf "\nPart 2: "
  37.         for (i in string_part2) {
  38.                 printf substr(string_part2[i], length(string_part2[i]), 1);
  39.         }
  40. }
  41.  
  42. func reverse(string,   i, result) {
  43.         for (i=1; i<=length(string); i++) {
  44.                 result = substr(string, i, 1) result;
  45.         }
  46.         return result;
  47. }
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement