const fs = require('fs/promises'); const sum = (arr) => arr.reduce((total, num) => total+num, 0); const arrayOfLength = n => Array.from(Array(n).keys()).map(() => {}); const modulo = (n, m) => ((n % m + m) % m); const keypress = async () => { process.stdin.setRawMode(true) return new Promise(resolve => process.stdin.once('data', data => { const byteArray = [...data] if (byteArray.length > 0 && byteArray[0] === 3) { console.log('^C') process.exit(1) } process.stdin.setRawMode(false) resolve() })) } const coords = ([x, y, z]) => `${x},${y},${z}`; const createNode = (arr, order, first, par, i = 0) => { const node = { val: arr[i], par } order.push(node); if(i < arr.length - 1) { node.next = createNode(arr, order, first || node, node, i+1) return node; } first.par = node; node.next = first; node.last = true; return node; }; const print = (node, first) => node === first ? [] : [node.val, ...print(node.next, first || node)]; const key = 811589153; const main = async () => { const input = (await fs.readFile("./input.txt", 'utf8')).slice(0, -1).split("\n").map(x => parseInt(x) * key); const order = []; let head = createNode(input, order, 0); const shiftIntoOffset = (node, offset) => { if(offset === 0) { return; } let replace = node.next; node.par.next = replace; replace.par = node.par; if(node === head) { head = node.next; } for(let i = 0; i < offset; ++i) { replace = replace.next; } if(replace === head) { head = node; } replace.par.next = node; node.par = replace.par; node.next = replace; replace.par = node; return; } const mix = () => { for(let i = 0; i < order.length; i++) { const node = order[i]; const shiftBy = modulo(node.val, input.length - 1); if(shiftBy !== 0) { shiftIntoOffset(node, shiftBy); } } }; for(let i = 0; i < 10; ++i) { mix(); } console.log("Mixed!"); const getAnswer = () => { const answer = []; let node = order.find(x => 0 === x.val); let i = 0; while(answer.length < 3) { if(i === 1000 % input.length || i === 2000 % input.length || i === 3000 % input.length ) { answer.push(node.val); } node = node.next; ++i; } return answer; }; console.log("Answer: ", sum(getAnswer())); } main();