Advertisement
rdm

Untitled

rdm
Jul 9th, 2012
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
J 2.13 KB | None | 0 0
  1. simpleDeltas =: (1 0),(0 _1),(_1 0),,:(0 1)
  2. eightdirDeltas =: (_1 1),(_1 _1),(1 _1),(1 1),simpleDeltas
  3.  
  4. indexOutOfBounds =: (0 > ]) +./@:, <: NB. x={vect}shapeOfArray, y={vect}index; z=bit
  5.  
  6. atIndex =: ({~ <@:|.)"_ 1 NB. equivalent of x[y2][...][y0] in C-style language
  7.  
  8. filter =: 1 : '((0~:u)"_1 y) # y' NB. removes all elements of y where u(y[i]) = 0
  9.  
  10. manhattanDistance =: +/@:|@:- NB. x={vect}, y={vect}; z={num}dist
  11.  
  12. shuffle =: (#?#) { ]
  13.  
  14. NB. x = [[bit]]  valid squares
  15. NB. y = [num]    index
  16. NB. z = [[num]]  neighbors
  17. gridNeighbors =: 4 : 0
  18.     neighbors =. simpleDeltas +"1 y
  19.     neighbors =. (-.@(($x)&indexOutOfBounds)) filter neighbors NB. remove those leaving the grid
  20.     neighbors =. x&atIndex filter neighbors NB. remove those entering a wall
  21. )
  22.  
  23. NB. Path<T> =: [{boxed num}distance, {boxed [T]}path]
  24.  
  25. NB. m = [[bit]]        valid squares
  26. NB. y = Path<tuple>
  27. NB. z = [Path<tuple>]  extended paths
  28. gridExtendPath =: 1 : 0
  29.     newDist  =. 1 + > {. y
  30.     path     =. > {: y
  31.     lastPos  =. {: path
  32.     newPoses =. m gridNeighbors lastPos
  33.     newPaths =. path ,"_ 1 newPoses
  34.     (newDist ; <)"_1 newPaths
  35. )
  36.  
  37. NB. x = Node                        goal
  38. NB. u = (Path<Node>)->[Path<Node>]  extendPath
  39. NB. v = (Node,Node)->num            heuristicDist
  40. NB. y = Node                        start
  41. NB. z = Path<Node>                  shortest path
  42. aStar =: 2 : 0
  43. :
  44.     closed   =. (0,$y) $ 0
  45.     frontier =. ,: 0;<,:y
  46.     while. #frontier do.
  47.         currentPath =. {. frontier
  48.         frontier    =. }. frontier
  49.         last        =. {: > {: currentPath
  50.         if. last e. closed do. continue.           end.
  51.         if. last -: x      do. currentPath return. end.
  52.         closed   =. closed, last
  53.         frontier =. frontier, (u currentPath)
  54.         NB. SORT FRONTIER
  55.         scores   =. (>@{. + (x v {:@:>@:{:))"_1 frontier
  56.         frontier =. frontier /: scores
  57.     end.
  58.     exception_message=:'No path found.' throw.
  59. )
  60.  
  61. exampleG =: 10 10 $ (0 0 0 0 1 1 0 0 1 1 0 1 1 0 1 1 0 0 1 1 1 0 0 1 1 1 1 1 0 0 1 0 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 1 0 0 1 1 0 1 1 1 1 0 1 0 0 1 0 0 1 1 0 1 0 1 1 1 0 1 1 0 0 1 1 1 0 1 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 0 1)
  62. exampleSolution =: 0 8 ((exampleG gridExtendPath) aStar manhattanDistance) 5 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement