Advertisement
Guest User

Untitled

a guest
Jan 21st, 2020
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.53 KB | None | 0 0
  1. function createMap(string) {
  2. return string.split('\n').map(row => row.split(''));
  3. }
  4.  
  5.  
  6.  
  7. function createGraph(map) {
  8. const graph = {}
  9. function linkNode(i,j, cost, dist) {
  10. return { i, j, cost, dist, dir };
  11. }
  12. function slide(startI, startJ, dir) {
  13. let dist = 0;
  14. let cost = 1;
  15. let stopI, stopJ;
  16. switch(dir) {
  17. case 'u':
  18. for (let i = startI; i >= 0; i--) {
  19. dist++;
  20. if(i === 0 || map[i][startJ] === 'x') [stopI, stopJ] = [i, startJ];
  21. if(map[i][startJ] === '#') [dist, stopI, stopJ] = [dist-1, i+1, startJ];
  22. }
  23. break;
  24. case 'd':
  25. for (let i = startI; i < map.length; i++) {
  26. dist++;
  27. if(i === map.length-1 || map[i][startJ] === 'x') [stopI, stopJ] = [i, startJ];
  28. if(map[i][startJ] === '#') [dist, stopI, stopJ] = [dist-1, i-1, startJ];
  29. }
  30. break;
  31. case 'r':
  32. for (let j = startJ; j < map[0].length; j++) {
  33. dist++;
  34. if(j === map[0].length-1 || map[startI][j] === 'x') [stopI, stopJ] = [startI, j];
  35. if(map[startI][j] === '#') [dist, stopI, stopJ] = [dist-1, startI, j-1];
  36. }
  37. break;
  38. case 'l':
  39. for (let j = startJ; j >= 0; j--) {
  40. dist++;
  41. if(j === 0 || map[startI][j] === 'x') [stopI, stopJ] = [startI, j];
  42. if(map[startI][j] === '#') [dist, stopI, stopJ] = [dist-1, startI, j+1];
  43. }
  44. break;
  45. }
  46. return {
  47. i: stopI,
  48. j: stopJ,
  49. cost, dist, dir
  50. };
  51. }
  52. function createNode(i, j) {
  53. const node = []
  54. //up
  55. if (i !== 0 && map[i-1][j] !== '#') {
  56. if (map[i][j] === ' ') node.push(slide(i, j, 'u'));
  57. node.push(linkNode(i-1, j, 1, 1, 'u'));
  58. }
  59. //down
  60. if (i !== map.length-1 && map[i+1][j] !== '#') {
  61. if (map[i][j] === ' ') node.push(slide(i, j, 'd'));
  62. node.push(linkNode(i+1, j, 1, 1, 'd'));
  63. }
  64. //right
  65. if (j !== map[0].length-1 && map[i][j+1] !== '#') {
  66. if (map[i][j] === ' ') node.push(slide(i, j, 'r'));
  67. node.push(linkNode(i, j+1, 1, 1, 'r'));
  68. }
  69. //left
  70. if (j !== 0 && map[i][j-1] !== '#') {
  71. if (map[i][j] === ' ') node.push(slide(i, j, 'l'));
  72. node.push(linkNode(i, j-1, 1, 1, 'l'));
  73. }
  74. }
  75. for (let i = 0; i < map.length; i++) {
  76. for (let j = 0; j < map[0].length; j++) {
  77. if (map[i][j] === '#') continue;
  78. graph[`${i},${j}`] = createNode(i, j);
  79. }
  80. }
  81. return graph;
  82.  
  83. }
  84. function IceMazeSolver(str) {
  85. const map = createMap(str);
  86. const graph = createGraph(map);
  87.  
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement