This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
In my code, I check for tail coordinates that I store in a dict (the key is in form: 12_-3, so x and y seperated by underscore).
Those coordinates change when the x or y distance with the head is more than abs(1). The code is doing what I want it to do, but I can't match the correct answer, it's actually quite a bit off (it gives me 4720 where I should get 6181).
If anyone sees where my logic is wrong, I would really appreciate the feedback.
https://gist.github.com/Barraka/a000b9447ac87b9ff87464d81b13c4d3
(javascript)
const temp1 = text.split(/\r?\n/);
const headCoordinates={x:0,y:0};
const tailCoordinates={x:0,y:0};
const visited={'0_0':'v'};
let score=1;
let line;
function checkVisited(x,y){
const coords=`${x}_${y}`;
if(!visited[coords]) {
visited[coords]==='v';
score ;
}
}
temp1.forEach( x=> {
line=x.split('');
const direction=line[0];
const distance=parseInt(line[2]);
if(direction==='L')headCoordinates.x-=distance;
if(direction==='R')headCoordinates.x =distance;
if(direction==='U')headCoordinates.y =distance;
if(direction==='D')headCoordinates.y-=distance;
//Check seperation
//Goes right
while(headCoordinates.x-tailCoordinates.x>1) {
tailCoordinates.x ;
if(headCoordinates.y!==tailCoordinates.y)tailCoordinates.y=headCoordinates.y;
checkVisited(tailCoordinates.x, tailCoordinates.y);
}
//Goes left
while(headCoordinates.x-tailCoordinates.x<-1) {
tailCoordinates.x--;
if(headCoordinates.y!==tailCoordinates.y)tailCoordinates.y=headCoordinates.y;
checkVisited(tailCoordinates.x, tailCoordinates.y);
}
//Goes up
while(headCoordinates.y-tailCoordinates.y>1) {
tailCoordinates.y ;
if(headCoordinates.x!==tailCoordinates.x)headCoordinates.x=tailCoordinates.x;
checkVisited(tailCoordinates.x, tailCoordinates.y);
}
//Goes down
while(headCoordinates.y-tailCoordinates.y<-1) {
tailCoordinates.y--;
if(headCoordinates.x!==tailCoordinates.x)headCoordinates.x=tailCoordinates.x;
checkVisited(tailCoordinates.x, tailCoordinates.y);
}
});
console.log('Score: ', score);
Thanks,
Subreddit
Post Details
- Posted
- 1 year ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/adventofcod...