|
| 1 | +#!/usr/bin/awk -f |
| 2 | + |
| 3 | +function extract_word(input, i, words) { |
| 4 | + patsplit(input, words, /[A-Za-z0-9]+/); |
| 5 | + return words[i]; |
| 6 | +} |
| 7 | + |
| 8 | +function direction_to_index_delta(direction) { |
| 9 | + if (direction == "right") return 1; |
| 10 | + if (direction == "left") return -1; |
| 11 | + |
| 12 | + print "Error: invalid direction", direction; |
| 13 | + exit 1; |
| 14 | +} |
| 15 | + |
| 16 | +BEGIN{RS="\n\n"} |
| 17 | + |
| 18 | +/^In state/ { |
| 19 | + split($0, rows, "\n"); |
| 20 | + |
| 21 | + in_state = extract_word(rows[1], 3); |
| 22 | + |
| 23 | + next_value_map[in_state, 0] = extract_word(rows[3], 4); |
| 24 | + next_index_delta_map[in_state, 0] = direction_to_index_delta(extract_word(rows[4], 6)); |
| 25 | + next_state_map[in_state, 0] = extract_word(rows[5], 4); |
| 26 | + |
| 27 | + next_value_map[in_state, 1] = extract_word(rows[7], 4); |
| 28 | + next_index_delta_map[in_state, 1] = direction_to_index_delta(extract_word(rows[8], 6)); |
| 29 | + next_state_map[in_state, 1] = extract_word(rows[9], 4); |
| 30 | + |
| 31 | + next; |
| 32 | +} |
| 33 | + |
| 34 | +/^Begin in state/{ |
| 35 | + split($0, rows, "\n"); |
| 36 | + current_state = extract_word(rows[1], 4); |
| 37 | + |
| 38 | + total_steps = extract_word(rows[2], 6); |
| 39 | +} |
| 40 | + |
| 41 | +END{ |
| 42 | + current_index = 0; |
| 43 | + |
| 44 | + while (total_steps--) { |
| 45 | + current_value = tape[current_index] || 0; |
| 46 | + next_state = next_state_map[current_state, current_value]; |
| 47 | + next_value = next_value_map[current_state, current_value]; |
| 48 | + next_index_delta = next_index_delta_map[current_state, current_value]; |
| 49 | + |
| 50 | + tape[current_index] = next_value; |
| 51 | + current_state = next_state; |
| 52 | + current_index += next_index_delta; |
| 53 | + } |
| 54 | + |
| 55 | + diagnostic_checksum = 0; |
| 56 | + for (i in tape) { |
| 57 | + diagnostic_checksum += tape[i]; |
| 58 | + } |
| 59 | + print diagnostic_checksum; |
| 60 | +} |
0 commit comments