Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- "use strict";
- const { Heap } = require('heap-js');
- var fs = require("fs");
- let t = Date.now();
- var file =__filename.slice(__dirname.length + 1, -3)+ ".txt";
- let data = fs.readFileSync(file, 'utf8').toString().split('\n').map(s => s.trim());
- let grid = data.join("").split('');
- let GRIDSIZE =Math.sqrt(grid.length);
- let MULTIPLIER = 5;
- let endX = GRIDSIZE*MULTIPLIER-1;
- let endY = GRIDSIZE*MULTIPLIER-1;
- let neighbors = [[-1,0],[1,0],[0,-1],[0,1]];
- class Node {
- constructor() {
- this.x=0;
- this.y=0;
- this.f = 0; // g+h;
- this.g = 9999; // cost so far
- this.h = 0; // distance to goal
- this.inOpen = false;
- this.isClosed = false;
- }
- };
- let graph = {
- nodes:[],
- openList: new Heap((a,b) => a.g - b.g)
- };
- function getNode( x, y){
- if(graph.nodes[x+"_"+y] == undefined)
- {
- let n = new Node();
- n.x = x;
- n.y = y;
- n.h = (endX - x) + (endY - y);
- graph.nodes[x+"_"+y]= n;
- }
- return graph.nodes[x+"_"+y];
- }
- let n = getNode(0,0);
- n.inOpen = true;
- n.g = 0;
- graph.openList.push(n)
- let destination = false;
- while (destination == false){
- let n = graph.openList.pop();
- if (n.x == endX && n.y == endY){
- destination = true;
- console.log("DONE!!!!");
- console.log(n.g);
- }
- else{
- n.inOpen = false;
- for (let edge of neighbors){
- let x = n.x+edge[0];
- let y = n.y+edge[1];
- if(x<0 || x>endX || y<0 || y>endY)
- continue;
- let n2 = getNode(x,y);
- if(n2.isClosed)
- continue;
- let oX = x % GRIDSIZE;
- let oY = y % GRIDSIZE;
- let gX = Math.floor(x / GRIDSIZE);
- let gY = Math.floor(y / GRIDSIZE);
- let gg = Number(grid[oY*GRIDSIZE + oX]) + gX + gY;
- if(gg>9){
- gg -= 9;
- }
- let g = n.g + gg;
- if( !n2.inOpen ){
- n2.g = g;
- // n2.f = g;
- n2.inOpen = true;
- graph.openList.push(n2);
- }else if (n2.g > g){
- n2.g = g;
- // n2.f = g;
- }
- }
- }
- n.isClosed = true;
- }
- console.log("----------------------");
- console.log(Date.now()-t);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement