Add 2023/Day 1/part2.js

This commit is contained in:
x0x7 2024-11-29 18:45:46 -05:00
parent 8c18d7f74c
commit 5c691a5e60
1 changed files with 61 additions and 0 deletions

61
2023/Day 1/part2.js Normal file
View File

@ -0,0 +1,61 @@
#!/usr/bin/env node
var number_words=`
0
1
2
3
4
5
6
7
8
9
zero
one
two
three
four
five
six
seven
eight
nine`;
number_words = number_words.split('\n').filter(i=>i);
function allneedles(stack,needle) {
var out=[];
var sent=-1;
while((sent=stack.indexOf(needle,sent+1))!=-1) {
//console.log({stack,needle,sent});
out.push(sent);
}
return out;
}
function translatelineintopositions(line) {
var out = [];
number_words.forEach((needle,index)=>{
var valueof = index%10;
var allof = allneedles(line,needle);
//console.log({line,needle,valueof,allof});
out=out.concat(allof.map(pos=>({pos,valueof})));
});
out.sort((a,b)=>a.pos-b.pos);
return out;
}
function linetonumber(line) {
var numbers = translatelineintopositions(line);
var out =numbers[0].valueof*10+numbers[numbers.length-1].valueof;
console.log({out});
return out;
}
var inputstring = require('fs').readFileSync('input.txt','utf8');
var lines = inputstring.split('\n').filter(i=>i);
var sum=0;
for(var line of lines) {
sum+=linetonumber(line);
}
console.log('Result:',sum);