import { loadFile } from "std"; var data = loadFile("3.txt"); var lines = data.split("\n"); var reg = /\d+/g; function is_partnum(number, line, last) { var left = last-number.length-1; left = left < 0 ? 0 : left; var up = line-1; var down = line+1; last++; if (last > lines[line].length-1) last = lines[line].length-1; var checks = []; if (up >= 0) checks.push(lines[up].slice(left,last)); checks.push(lines[line].slice(left,last)); if (down < lines.length) checks.push(lines[down].slice(left,last)); for (var i = 0; i < checks.length; i++) if (checks[i].match(/[^\.\d]/)) return true; return false; } var str; var total = 0; for (var i = 0; i < lines.length; i++) while (str = reg.exec(lines[i])) if (is_partnum(str[0], i, reg.lastIndex)) total += Number(str[0]); console.log("Part 1:"); console.log(total); var greg = /\*/g; function get_number(line, p) { var l = p; var r = p; var str = lines[line]; while (l >= 0 && str[l].match(/\d/)) l--; l++; while (r < str.length && str[r].match(/\d/)) r++; return Number(str.slice(l,r)); } function gear_ratio(line, p) { var checks = []; var left = p-1; left = left < 0 ? 0 : left; var right = p + 2; right = right > lines[line].length-1 ? lines[line].length-1 : right; var up = line-1; var down = line+1; checks.push(line); if (up >= 0) checks.push(up); if (down < lines.length) checks.push(down); var reglet = /\d+/g; var coords = []; var n; checks.forEach(function(c) { while (n = reglet.exec(lines[c].slice(left,right))) { coords.push({ line: c, idx:reglet.lastIndex-1+left }); } }); if (coords.length !== 2) return 0; var n = 1; coords.forEach(function(c) { var x = get_number(c.line, c.idx); n *= x; }); return n; } total = 0; for (var i = 0; i < lines.length; i++) while(str = greg.exec(lines[i])) total += gear_ratio(i, greg.lastIndex-1); console.log("Part 2:"); console.log(total);