Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. (() => {
  2. const dim = 7;
  3. const graph = {};
  4. const path = [];
  5.  
  6. // create graph
  7. for (let i = 0; i < dim*dim; i++) {
  8. const row = i % dim;
  9. const col = Math.floor(i / dim);
  10. const edges = [
  11. getIndex(row + 1, col),
  12. getIndex(row -1, col),
  13. getIndex(row, col + 1),
  14. getIndex(row, col - 1),
  15. ].filter(e => e != null);
  16. graph[i] = {
  17. edges: shuffle(edges),
  18. };
  19. }
  20.  
  21. // create maze path
  22. explore(graph, 0);
  23.  
  24. console.log('graph:', graph);
  25. console.log('path:', path);
  26.  
  27. function getIndex(row, col) {
  28. if (row >= dim || row < 0 || col >= dim || col < 0) return null;
  29. return (col * dim) + row;
  30. }
  31.  
  32. function shuffle(array) {
  33. for(let i = 0; i < array.length; i++){
  34. const randomIndex = Math.floor(Math.random() * array.length);
  35. const temp = array[i];
  36. array[i] = array[randomIndex];
  37. array[randomIndex] = temp;
  38. }
  39. return array;
  40. }
  41.  
  42. function explore(graph, currentIndex) {
  43. const current = graph[currentIndex];
  44. current.visited = true;
  45. for (let i = 0; i < current.edges.length; i++) {
  46. const nextIndex = current.edges[i];
  47. const next = graph[nextIndex];
  48. if (!next.visited) {
  49. path.push([currentIndex, nextIndex]);
  50. explore(graph, nextIndex);
  51. }
  52. }
  53. }
  54.  
  55. })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement