Skip to content

Commit

Permalink
solved bonus challenge
Browse files Browse the repository at this point in the history
  • Loading branch information
chinesedfan committed Oct 17, 2017
1 parent 61f6514 commit 9b62e7c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 24 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,3 +81,10 @@ For hardness: S(Simple), M(Middle), H(Hard).
| 23 | S/M | cpu/optimization |
| 24 | M/M | bfs, permutation |
| 25 | S/- | cpu, find first |

## Bonus

Download `input.txt` [here](https://gist.githubusercontent.com/topaz/15518587415ccd0468767aed4192bfd3/raw/c5bfd6a7d40eabe1ae8b9a0fb36a939cb0c5ddf4/bonuschallenge.txt).

- `YEAR=2016 node index.js 26 < input.txt > bonus.out.1`
- `YEAR=2016 node index.js 8 2 < bonus.out.1`
33 changes: 9 additions & 24 deletions lib/2016/day26.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
'use strict';
const _ = require('lodash');
const rInstr = /(\w+) ([a-d]|-?\d+)(?: ([a-d]|-?\d+))?/;
const jnzCache = {};
const output = [];

module.exports = function(part, data) {
const instrs = _.map(data.split('\n'), (line) => rInstr.exec(line));
let ip = 0;
let regs = {
a: part == 1 ? 7 : 12,
a: 0,
b: 0,
c: 0,
d: 0
Expand All @@ -16,7 +16,6 @@ module.exports = function(part, data) {
while (ip < instrs.length) {
ip = exec(regs, instrs, ip);
}
console.log(ip + ':', regs.a, regs.b, regs.c, regs.d);
};

function exec(regs, instrs, ip) {
Expand All @@ -34,30 +33,16 @@ function exec(regs, instrs, ip) {
regs[matches[2]]--;
break;
case 'jnz':
// try to find multiply
if (/[a-d]/.test(matches[2])) {
if (jnzCache[ip]) {
const k = matches[2];
const step = jnzCache[ip][k] / (jnzCache[ip][k] - regs[k]);
_.each(regs, (val, key) => {
regs[key] = jnzCache[ip][key] + (regs[key] - jnzCache[ip][key]) * step;
});
delete jnzCache[ip];
} else {
jnzCache[ip] = _.clone(regs);
}
}

if (getVal(regs, matches[2])) return ip + getVal(regs, matches[3]);
break;
case 'tgl':
const target = instrs[ip + getVal(regs, matches[2])];
if (!target) break;

if (typeof target[3] == 'undefined') {
target[1] = target[1] == 'inc' ? 'dec' : 'inc';
case 'out':
const val = getVal(regs, matches[2]);
const ch = String.fromCharCode(val);
if (ch == '\n') {
console.log(output.join(''));
output.length = 0;
} else {
target[1] = target[1] == 'jnz' ? 'cpy' : 'jnz';
output.push(ch);
}
break;
default:
Expand Down

0 comments on commit 9b62e7c

Please sign in to comment.