diff --git a/2023/Day 1/part2.js b/2023/Day 1/part2.js new file mode 100644 index 0000000..14dacf7 --- /dev/null +++ b/2023/Day 1/part2.js @@ -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); \ No newline at end of file