enkryptor

Untitled

Feb 17th, 2022
876
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. function knight(start, finish) {
  3.   const s = getCoords(start)
  4.   const f = getCoords(finish)
  5.   return getShortestPath(s.x, s.y, f.x, f.y, new Set(), 0)
  6. }
  7.  
  8. function getShortestPath(startX, startY, targetX, targetY, visited, len) {
  9.   if (startX === targetX && startY === targetY) {
  10.     return len
  11.   }
  12.   visited.add(`${startX}:${startY}`)
  13.   const paths = [...getPaths(startX, startY)]
  14.     .filter(p => isInBounds(p) && !visited.has(`${p.x}:${p.y}`))
  15.     .map(p => getShortestPath(p.x, p.y, targetX, targetY, visited, len + 1))
  16.     .filter(x => !Number.isNaN(x))
  17.   return paths.length > 0 ? Math.min(...paths) : NaN
  18. }
  19.  
  20. function getCoords(str) {
  21.   return {
  22.     x: 'abcdefgh'.indexOf(str[0]),
  23.     y: Number(str[1]) - 1
  24.   }
  25. }
  26.  
  27. function* getPaths(x, y) {
  28.   yield {x: x+2, y: y+1}
  29.   yield {x: x+2, y: y-1}
  30.   yield {x: x-2, y: y+1}
  31.   yield {x: x-2, y: y-1}
  32.   yield {x: x+1, y: y+2}
  33.   yield {x: x+1, y: y-2}
  34.   yield {x: x-1, y: y+2}
  35.   yield {x: x-1, y: y-2}
  36. }
  37.  
  38. function isInBounds(p) {
  39.   return p.x >= 0 && p.x < 8 && p.y >= 0 && p.y < 8
  40. }
  41.  
Advertisement
Add Comment
Please, Sign In to add comment