Advertisement
mosredna

AoC 2021 day 15 part 2 Node.js

Dec 15th, 2021 (edited)
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. "use strict";
  2. const { Heap } = require('heap-js');
  3. var fs = require("fs");
  4.  
  5. let t = Date.now();
  6.  
  7. var file =__filename.slice(__dirname.length + 1, -3)+ ".txt";
  8. let data = fs.readFileSync(file, 'utf8').toString().split('\n').map(s => s.trim());
  9.  
  10. let grid = data.join("").split('');
  11.  
  12. let GRIDSIZE =Math.sqrt(grid.length);
  13. let MULTIPLIER = 5;
  14. let endX = GRIDSIZE*MULTIPLIER-1;
  15. let endY = GRIDSIZE*MULTIPLIER-1;
  16. let neighbors = [[-1,0],[1,0],[0,-1],[0,1]];
  17.  
  18. class Node {
  19.   constructor() {
  20.    this.x=0;
  21.    this.y=0;
  22.  
  23.    this.f = 0; // g+h;
  24.    this.g = 9999; // cost so far
  25.    this.h = 0; // distance to goal
  26.    this.inOpen = false;
  27.    this.isClosed = false;
  28.   }
  29. };
  30.  
  31. let  graph = {
  32.   nodes:[],
  33.   openList: new Heap((a,b) => a.g - b.g)
  34. };
  35.  
  36.  
  37. function getNode( x,  y){
  38.   if(graph.nodes[x+"_"+y] == undefined)
  39.   {
  40.     let n = new Node();
  41.     n.x = x;
  42.     n.y = y;
  43.     n.h = (endX - x) + (endY - y);
  44.     graph.nodes[x+"_"+y]= n;
  45.   }
  46.   return graph.nodes[x+"_"+y];
  47. }
  48.  
  49. let n = getNode(0,0);
  50. n.inOpen = true;
  51. n.g = 0;
  52. graph.openList.push(n)
  53. let destination = false;
  54.  
  55. while (destination == false){
  56.   let n = graph.openList.pop();
  57.   if (n.x == endX && n.y == endY){
  58.     destination = true;
  59.     console.log("DONE!!!!");
  60.     console.log(n.g);
  61.   }
  62.   else{
  63.  
  64.     n.inOpen = false;
  65.  
  66.     for (let edge of neighbors){
  67.      
  68.       let x = n.x+edge[0];
  69.       let y = n.y+edge[1];
  70.       if(x<0 || x>endX || y<0 || y>endY)
  71.         continue;
  72.  
  73.       let n2 = getNode(x,y);
  74.      
  75.       if(n2.isClosed)
  76.         continue;
  77.  
  78.       let oX = x % GRIDSIZE;
  79.       let oY = y % GRIDSIZE;
  80.       let gX = Math.floor(x / GRIDSIZE);
  81.       let gY = Math.floor(y / GRIDSIZE);
  82.  
  83.       let gg = Number(grid[oY*GRIDSIZE + oX]) + gX + gY;
  84.  
  85.       if(gg>9){
  86.         gg -= 9;
  87.       }
  88.  
  89.       let g = n.g + gg;
  90.  
  91.       if( !n2.inOpen ){
  92.         n2.g = g;
  93.        // n2.f = g;
  94.         n2.inOpen = true;
  95.        
  96.         graph.openList.push(n2);
  97.       }else if (n2.g > g){
  98.         n2.g = g;
  99.       //  n2.f = g;
  100.       }
  101.      
  102.     }
  103.   }
  104.   n.isClosed = true;
  105. }
  106.  
  107. console.log("----------------------");
  108. console.log(Date.now()-t);
  109.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement