AdventOfCodeSolutions/2023/Day 1/part2_first_attempt.js

55 lines
1.3 KiB
JavaScript

#!/usr/bin/env node
var inputstring = require('fs').readFileSync('input.txt','utf8');
var regs = [/zero/g,/one/g,/two/g,/three/g,/four/g,/five/g,/six/g,/seven/g,/eight/g,/nine/g];
var lines = inputstring.split('\n').filter(i=>i);
var minNumerical = '0'.charCodeAt(0);
var maxNumerical = '9'.charCodeAt(0);
function convertline(line) {
for(var i in regs) {
line = line.replace(regs[i],`${i}`);
}
return line;
}
function greedyconvertline(line) {
if(line.length<3) return line;
for(var scopelength=3;scopelength<=line.length;++scopelength) {
var first = line.substr(0,scopelength);
var second = line.substr(scopelength);
var newline = convertline(first)+second;
var diff=0;
if(newline.length!=line.length) {
diff=(line.length-newline.length);
}
//console.log({line,scopelength,first,second,newline,diff})
scopelength-=diff;
line=newline;
}
return line;
}
lines = lines.map(greedyconvertline);
//console.log({lines});
function onlynumerical(str) {
return str.split('').map(i=>i.charCodeAt(0)).filter(i=>(i>=minNumerical && i<=maxNumerical)).map(i=>i-48);
}
function firstandlast(arr) {
return [arr[0],arr[arr.length-1]];
}
var nums = lines.map(i=>{
var nums = firstandlast(onlynumerical(i));
//console.log({nums});
return nums[0]*10+nums[1];
});
//console.log({nums});
var sum=0;
for(var i of nums) {
sum+=i;
}
console.log(sum);