advent-of-code/2019/02/day2.awk

47 lines
1.1 KiB
Awk
Raw Permalink Normal View History

2019-12-02 14:57:01 +01:00
#!/usr/bin/awk -f
2019-12-02 11:59:35 +01:00
# There are no scopes, so we just write to `arr` here and use it later.
# Returning the array does not seem to be legal either. Only scalars allowed.
function prepareInput(raw) {
len = split(raw, arr, ",");
2019-12-02 10:28:24 +01:00
for (i=0; i<=len; i++) {
2019-12-02 11:59:35 +01:00
arr[i-1] = int(arr[i]);
2019-12-02 10:28:24 +01:00
}
2019-12-02 12:10:53 +01:00
return len;
2019-12-02 11:59:35 +01:00
}
2019-12-02 12:10:53 +01:00
function process(arr, len, first, second) {
arr[1] = first
arr[2] = second
2019-12-02 10:28:24 +01:00
for (i=0; i<len; i+=4) {
2019-12-02 11:59:35 +01:00
cmd = arr[i];
e1 = arr[i+1];
e2 = arr[i+2];
target = arr[i+3];
2019-12-02 09:58:11 +01:00
if (cmd == 1)
arr[target] = arr[e1] + arr[e2];
else if (cmd == 2)
arr[target] = arr[e1] * arr[e2];
else if (cmd == 99)
break;
else
print "Error, invalid command";
}
2019-12-02 11:59:35 +01:00
}
{
len = prepareInput($1);
2019-12-02 12:10:53 +01:00
process(arr, len, 12, 2);
printf("Part 1: %d\n", arr[0]);
2019-12-02 14:57:01 +01:00
part2_target = 19690720
2019-12-02 12:10:53 +01:00
for (x=0; x<100; x++) {
for (y=0; y<100; y++) {
len = prepareInput($1);
process(arr, len, x, y);
2019-12-02 14:57:01 +01:00
if (arr[0] == part2_target) {
printf("Part 2: %d\n", 100 * x + y);
2019-12-02 12:10:53 +01:00
}
}
}
2019-12-02 09:58:11 +01:00
}