r/adventofcode • • Dec 12 '16

SOLUTION MEGATHREAD --- 2016 Day 12 Solutions ---

--- Day 12: Leonardo's Monorail ---

Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag/whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with "Help".


MUCH ADVENT. SUCH OF. VERY CODE. SO MANDATORY. [?]

This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

8 Upvotes

159 comments sorted by

View all comments

Show parent comment

2

u/AndrewGreenh Dec 12 '16

You gave me an idea! You said "why parse the instruction every tick with a regex?" I took it one step further: "Why recompute a state transition on every tick?" So I precomputet functions for each instruction that take a state and return a new state! Runs in 1.1s and is very terse :)

const _ = require('lodash');
const thunks = require('../getInput')(12, 2016).trim().split('\n').map(toThunk);

function getResult(thunks, state) {
  while (state.index >= 0 && state.index < thunks.length) thunks[state.index](state);
  return state;
}

function toThunk(instruction) {
  const [command, ...rest] = instruction.split(' ');
  const thunkGettersByCommand = {
    cpy: ([value, reg]) => (_.isNaN(+value) ?
      state => { state.index++; state.registers[reg] = state.registers[value]; } :
      state => { state.index++; state.registers[reg] = +value; }),
    inc: ([reg]) => state => { state.index++; state.registers[reg]++; },
    dec: ([reg]) => state => { state.index++; state.registers[reg]--; },
    jnz: ([check, jump]) => (_.isNaN(+check) ?
      state => { if (state.registers[check] !== 0) state.index += jump - 1; state.index++; } :
      state => { if (check !== 0) state.index += jump - 1; state.index++; }),
  };
  return thunkGettersByCommand[command](rest);
}

console.time('result');
console.log(getResult(thunks, { index: 0, registers: { a: 0, b: 0, c: 0, d: 0 } }));
console.log(getResult(thunks, { index: 0, registers: { a: 0, b: 0, c: 1, d: 0 } }));
console.timeEnd('result');

2

u/Twisol Dec 12 '16

Nice! You can actually improve on the jnz thunking -- if the check value is a literal, you can produce a no-op function if it's zero and generate an if-less jumping function if it's nonzero.