var moves = [[1, 0], [0, -1], [-1, 0], [0, 1]]; var coords = [0, 0]; var input = "R1, R1, R3, R1, R1, L2, R5, L2, R5, R1, R4, L2, R3, L3, R4, L5, R4, R4, R1, L5, L4, R5, R3, L1, R4, R3, L2, L1, R3, L4, R3, L2, R5, R190, R3, R5, L5, L1, R54, L3, L4, L1, R4, R1, R3, L1, L1, R2, L2, R2, R5, L3, R4, R76, L3, R4, R191, R5, R5, L5, L4, L5, L3, R1, R3, R2, L2, L2, L4, L5, L4, R5, R4, R4, R2, R3, R4, L3, L2, R5, R3, L2, L1, R2, L3, R2, L1, L1, R1, L3, R5, L5, L1, L2, R5, R3, L3, R3, R5, R2, R5, R5, L5, L5, R2, L3, L5, L2, L1, R2, R2, L2, R2, L3, L2, R3, L5, R4, L4, L5, R3, L4, R1, R3, R2, R4, L2, L3, R2, L5, R5, R4, L2, R4, L1, L3, L1, L3, R1, R2, R1, L5, R5, R3, L3, L3, L2, R4, R2, L5, L1, L1, L5, L4, L1, L1, R1"; var steps = input.replace(/L/g, "R0, R0, R").split(", ").map((a)=>parseInt(a.substr(1))); var locations = []; function addCoord(x, y){ if(!locations[x]){ locations[x] = []; } if(!locations[x][y]){ locations[x][y] = 0; } locations[x][y]++; } var coords = [0, 0] for(var step in steps){ for(var i = 0; i < steps[step]; i++){ coords = [coords[0] + moves[step%4][0], coords[1] + moves[step%4][1]]; addCoord(coords[0], coords[1]); if(locations[coords[0]][coords[1]] == 2){ console.log(coords); console.log(coords.map(Math.abs).reduce((a, b)=>(a + b))); } } }