letranks=['a','b','c','d','e','f','g','h'];letfiles=['1','2','3','4','5','6','7','8'];letallMoves=[[1,2],[1,-2],[-1,2],[-1,-2],[2,1],[2,-1],[-2,1],[-2,-1]];/**
* Search for the required moves to move a knight between two squares
*
* @param position
* @param target
* @returns {*}
*/functionmoveSearch(position,target){letstack=[];// maintain an ordered stack so that we choose the 'best first'stack.push({position:positionToArray(position),moves:[]});while(stack.length!==0){letmove=stack.pop();letposition=move.position;// If the current position is the target, then we're done and we can send back the moves we've// takenif(arrayToPosition(move.position)===target){return[...move.moves,position].map(arrayToPosition);}// Otherwise, we need to get the candidate moves from this list, and place them on the stackpruneMoves(position).map(move=>{// Apply the moveletrank=position[0]+move[0];letfile=position[1]+move[1];return[rank,file];}).forEach(item=>{// Don't allow doubling backif(move.moves.map(arrayToPosition).includes(arrayToPosition(item))){return;}// Push the move to the stackstack.push({position:item,moves:[...move.moves,position]});});// Check the candidate with the fewest moves so far, otherwise choose the one// that's closeststack.sort((a,b)=>{if(a.moves.length!==b.moves.length){returnb.moves.length-a.moves.length;}letaDistance=calculateDistance(a.position,positionToArray(target));letbDistance=calculateDistance(b.position,positionToArray(target));returnbDistance-aDistance;});}// we shouldn't really reach here -- this signifies that it's impossiblereturn[];}/**
* Takes all the available knight moves, and return the ones that keep it on the board
*
* @param position
* @returns {*[]}
*/functionpruneMoves(position){returnallMoves.filter((move)=>{letrank=position[0]+move[0];letfile=position[1]+move[1];returnrank>=0&&rank<ranks.length&&file>=0&&file<files.length;});}/**
* Converts a chess position to an array
*
* @param move
* @returns {*[]}
*/functionpositionToArray(move){letchars=move.split('');return[ranks.indexOf(chars[0]),files.indexOf(chars[1])];}/**
* Converts an array to a chess position
*
* @param arr
* @returns {string}
*/functionarrayToPosition(arr){returnranks[arr[0]]+files[arr[1]];}/**
* Calculates the distance between two positions
* @param pos1 array the first position
* @param pos2 array the second position
* @returns {number} the distance between the two positions
*/functioncalculateDistance(pos1,pos2){// Take the euclidean distance using a2 + b2 = c2letrankDistance=pos1[0]-pos2[0];letfileDistance=pos1[1]-pos2[1];returnMath.sqrt(Math.pow(rankDistance,2)+Math.pow(fileDistance,2));}
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.
Messy, inefficient JavaScript solution