import { loadFile } from "std"; var datafile = "11.txt"; var data = loadFile(datafile).trim().split('\n'); String.prototype.insert = function(index, string) { if (index > 0) { return this.substring(0, index) + string + this.substring(index, this.length); } return string + this; }; var xb = []; var yb = []; for (var i = data.length-1; i >= 0; i--) { if (!data[i].match('#')) yb.push(i); } colm: for (var i = data[0].length-1; i >= 0; i--) { for (var j = 0; j < data.length; j++) if (data[j][i] === '#') continue colm; xb.push(i); } var galaxies = []; for (var i = 0; i < data.length; i++) for (var j = 0; j < data[i].length; j++) if (data[i][j] === '#') galaxies.push([i,j]); var sum = 0; var expansion = 2; function galaxy_dist(a,b) { var x = a[0] <= b[0] ? a[0] : b[0]; var y = a[1] <= b[1] ? a[1] : b[1]; var dx = Math.abs(a[0]-b[0]); var dy = Math.abs(a[1]-b[1]); var xs = yb.filter(q => q > x && q < x+dx); var ys = xb.filter(q => q > y && q < y+dy); return dx+dy+(xs.length*(expansion-1))+(ys.length*(expansion-1)); } for (var i = 0; i < galaxies.length; i++) for (var j = i+1; j < galaxies.length; j++) sum += galaxy_dist(galaxies[i], galaxies[j]); console.log("Part 1:"); console.log(sum); expansion = 1000000; sum = 0; for (var i = 0; i < galaxies.length; i++) for (var j = i+1; j < galaxies.length; j++) sum += galaxy_dist(galaxies[i], galaxies[j]); console.log("Part 2:"); console.log(sum);