classNode{constructor(value){this.value=value;this.right=this;this.left=this;}addToRight(neighbor){if(this.right){this.right.left=neighbor;}neighbor.right=this.right;neighbor.left=this;this.right=neighbor;}visitLeft(times=1){letnode=this;for(leti=0;i<times;i++){node=node.left}returnnode;}remove(){constleft=this.left;constright=this.right;left.right=right;right.left=left;this.right=null;this.left=null;}}constparseInput=input=>{constinputRegex=/^(?<players>\d+) players; last marble is worth (?<marbles>\d+) points$/;const{players,marbles}=input.match(inputRegex).groups;return{players:+players,marbles:+marbles};};constgetPlayerScores=(players,marbles)=>{constplayerScores=Array.from({length:players},p=>0);letcurrentMarble=newNode(0);for(leti=1;i<=marbles;i++){constnewMarble=newNode(i);if(i%23>0){currentMarble.right.addToRight(newMarble);currentMarble=newMarble;}else{constcurrentPlayer=i%players;constmarbleToBeRemoved=currentMarble.visitLeft(7);playerScores[currentPlayer]+=i+marbleToBeRemoved.value;currentMarble=marbleToBeRemoved.right;marbleToBeRemoved.remove();}}returnplayerScores;}module.exports={parseInput,getPlayerScores};
09a.js
const{readFile}=require('./reader');const{parseInput,getPlayerScores}=require('./09-common');(async()=>{constlines=awaitreadFile('09-input.txt');const{players,marbles}=parseInput(lines[0]);constplayerScores=getPlayerScores(players,marbles);consthighScore=Math.max(...playerScores.values());console.log(`The highest score is ${highScore}`);})();
09b.js
const{readFile}=require('./reader');const{parseInput,getPlayerScores}=require('./09-common');(async()=>{constlines=awaitreadFile('09-input.txt');const{players,marbles}=parseInput(lines[0]);constplayerScores=getPlayerScores(players,marbles*100);consthighScore=Math.max(...playerScores.values());console.log(`The highest score is ${highScore}`);})();
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
JavaScript solution
The trick for this one is to use a circular linked list. You need to handle pointers to both right and left nodes for each addition and removal.
Then, traversing clockwise is just moving rightward and counter-clockwise is leftward.
reader.js
09-common.js
09a.js
09b.js