I decided to solve this year’s Advent of Code problems using awk(1), a woefully underutilised unix tool and programming language. The below solutions may be run using the command:
awk -f solution.awk input.txt
{ total += int($0 / 3.0) - 2 }
END { print total }
{
fuel = int($0 / 3.0) - 2;
while (fuel > 0) {
total += fuel;
fuel = int(fuel / 3.0) - 2;
}
}
END { print total }
These are a fair bit less elegant than the previous two solutions. I’m not entirely happy with the second, in particular the array copy, but it works.
BEGIN { RS = "," }
{ ops[i++] = $1 }
END {
for (i = 0; ops[i] != 99; i += 4) {
if (ops[i] == 1)
ops[ops[i+3]] = ops[ops[i+1]] + ops[ops[i+2]];
else if (ops[i] == 2)
ops[ops[i+3]] = ops[ops[i+1]] * ops[ops[i+2]];
}
print ops[0];
}
BEGIN { RS = "," }
{ oops[i++] = $1 }
END {
for (noun = 0; noun <= 99; noun++)
for (verb = 0; verb <= 99; verb++) {
for (op in oops) ops[op] = oops[op];
ops[1] = noun;
ops[2] = verb;
for (i = 0; ops[i] != 99; i += 4) {
if (ops[i] == 1)
ops[ops[i+3]] = ops[ops[i+1]] + ops[ops[i+2]];
else if (ops[i] == 2)
ops[ops[i+3]] = ops[ops[i+1]] * ops[ops[i+2]];
}
if (ops[0] == 19690720) {
print 100*noun + verb;
exit 0;
}
}
}
© 2019 Joe Davis.