My brute force JS code. Still looking into a more optimized solution
constclosestIntersectionToOrigin=(wirePath1,wirePath2)=>{consttrace1=traceWire(wirePath1);consttrace2=traceWire(wirePath2);// find intersection of tracesconstintersects=trace1.filter(x=>trace2.includes(x));constdistanceArr=intersects.slice(1).map(x=>manhattanDistance([0,0],x.split(',').map(Number)));returnMath.min(...distanceArr);};constleastStepsIntersection=(wirePath1,wirePath2)=>{consttrace1=traceWire(wirePath1);consttrace2=traceWire(wirePath2);// find intersection of tracesconstintersects=trace1.filter(x=>trace2.includes(x));constdistanceArr=intersects.slice(1).map(x=>{consttotalSteps=trace2.findIndex(y=>y==x)+trace1.findIndex(y=>y==x);returntotalSteps;});returnMath.min(...distanceArr);};consttraceWire=(wirePath,acc=['0,0'])=>{for(leti=0;i<wirePath.length;i++){constmove=wirePath[i];constdirection=move[0];conststeps=Number(move.slice(1));conststart=acc[acc.length-1].split(',').map(Number);let[x,y]=start;conststepMap={R:()=>`${x},${++y}`,L:()=>`${x},${--y}`,U:()=>`${++x},${y}`,D:()=>`${--x},${y}`};for(letj=0;j<steps;j++){acc.push(stepMap[direction]());}}returnacc;};constmanhattanDistance=(pos1,pos2)=>Math.abs(pos2[0]-pos1[0])+Math.abs(pos2[1]-pos1[1]);if(!module.parent){constwire1=['R75','D30','R83','U83','L12','D49','R71','U7','L72'];constwire2=['U62','R66','U55','R34','D71','R55','D58','R83'];console.log(leastStepsIntersection(wire1,wire2));}module.exports={closestIntersectionToOrigin,leastStepsIntersection};
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.
My brute force JS code. Still looking into a more optimized solution