61 lines
1.0 KiB
JavaScript
61 lines
1.0 KiB
JavaScript
|
#!/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);
|