import * as std from 'std' var data = std.loadFile("16.txt"); data = data.trim().split('\n'); console.log(`grid is ${data[0].length}x${data.length}, total of ${data[0].length*data.length}`); var in_grid = function(c) { if (c[0] >= 0 && c[0] < data[0].length && c[1] >= 0 && c[1] < data.length) return true; return false; } function measure_power(start) { var e = 0; /* Energize the tile that beam b is on. If the tile has already seen thsis beam config, return false/ */ var energize = function(b) { if (!in_grid(b.pos)) return false; var sc = JSON.stringify(b.pos); var bs = JSON.stringify(b); if (!energize.cache[sc]) energize.cache[sc] = {}; if (energize.cache[sc][bs]) return false; energize.cache[sc][bs] = true; return true; } energize.cache = {}; var energized = function() { return Object.keys(energize.cache).length; } var beams = [{pos:start.pos.slice(), dir: start.dir.slice()}]; while(beams.length) { beams.forEach(function(beam) { if (!energize(beam)) { beam.kill = true; return; } var c = data[beam.pos[1]][beam.pos[0]]; switch(c) { case '\\': beam.dir = [beam.dir[1],beam.dir[0]]; break; case '/': beam.dir = [-beam.dir[1],-beam.dir[0]]; break; case '-': if (beam.dir[1]) { beam.dir = [1,0]; var m = {pos:beam.pos.slice(),dir:[-1,0]}; m.pos[0]--; beams.push(m); } break; case '|': if (beam.dir[0]) { beam.dir = [0,1]; var m = {pos:beam.pos.slice(),dir:[0,-1]}; m.pos[1]--; beams.push(m); } break; } beam.pos[0] += beam.dir[0]; beam.pos[1] += beam.dir[1]; }); beams = beams.filter(b => typeof b.kill === 'undefined'); } return energized(); } var start = {pos:[0,0], dir: [1,0]}; console.log('silver:'); console.log(measure_power(start)); var starts = []; for (var i = 0; i < data.length; i++) { starts.push({pos:[0,i], dir:[1,0]}); starts.push({pos:[i,0], dir:[0,1]}); starts.push({pos:[data.length-1,i], dir:[-1,0]}); starts.push({pos:[i,data.length-1],dir:[0,-1]}); } var high = 0; starts.forEach(function(s) { var e = measure_power(s); if (e > high) high = e; }); console.log("gold:"); console.log(high);