import * as std from 'std'; //var data = std.loadFile('14.txt'); //data = data.trim().split('\n').map(k=>k.split('')); function roll(line,x,dir) { if (data[line][x] !== 'O') return; var nline = line-dir[0]; var nx = x-dir[1]; if (nline < 0 || nx < 0 || nline === data.length || nx === data[0].length) return; if (data[nline][nx] === '.') { data[nline][nx] = 'O'; data[line][x] = '.'; roll(nline,nx,dir); } } var cache = {}; cache.north = {}; cache.south = {}; cache.east = {}; cache.west = {}; function make_table() { return JSON.stringify(data); } function print_table() { data.forEach(p=>console.log(p)); console.log("");} var cdirs = { north: [1,0], south: [-1,0], west: [0,1], east: [0,-1] }; var data = std.loadFile('14.test'); data = data.trim().split('\n').map(k=>k.split('')); var h = data.length; var len = data[0].length; console.log(len); function tilt(dir) { var idx = undefined; var table = make_table(); if (cache[dir][table]) { idx = cache[dir][table].idx; data = JSON.parse(cache[dir][table].tb); return idx; } var vdir = cdirs[dir]; var rev = (dir === 'south' || dir === 'east'); if (!rev) for (var i = 0; i < data.length; i++) for (var j = 0; j < data[0].length; j++) roll(i,j,vdir); else for (var i = data.length-1; i >= 0; i--) for (var j = data[i].length-1; j >= 0; j--) roll(i,j,vdir); var t = {}; t.idx = Object.keys(cache[dir]).length; t.tb = JSON.stringify(data); cache[dir][table] = t; return t.idx; } function cycle() { var rr = []; rr.push(tilt('north')); rr.push(tilt('west')); rr.push(tilt('south')); rr.push(tilt('east')); if (!rr.every(r=>r)) return undefined; return rr; } var lastcycle = undefined; for (var i = 0; i < 1000000000; i++) { var cc = cycle(); if (lastcycle && cc) if (JSON.stringify(cc) === JSON.stringify(lastcycle)) break; lastcycle = cc; } var sum = 0; sum = data.reduce((acc,line,i) => acc += (line.filter(c => c === 'O').length*(h-i)), 0); console.log(sum);