TypeScript

by SHELDON PASCIAK

TypeScript

let maze: number[][] = [];
let rows=20;
let cols=20;
let odds=.87;
console.log("");console.log("");console.log("");console.log("");console.log("");console.log("");console.log("");console.log("");console.log("");console.log("");console.log("");console.log("");console.log("");console.log("");console.log("");console.log("");console.log("");console.log("");console.log("");console.log("");console.log("");console.log("");console.log("");console.log("");console.log("");console.log("");console.log("");console.log("");
type Point = [number, number];

for (let i = 0; i < rows; i++) {
  maze[i] = [];
  for (let j = 0; j < cols; j++) {
    if (i === 0 || i === cols-1 || j === 0 || j === rows-1) {
      maze[i][j] = 1;
    } else {
      maze[i][j] = Math.random() >= odds ? 1 : 0;
    }
  }
} 

const start: Point = [1, 1];
const end: Point = [rows-2, cols-2];
const path: Point[] = [];

function findPath(maze: number[][], start: Point, end: Point, path: Point[]): boolean {
  if (start[0] < 0 || start[0] >= maze.length || start[1] < 0 || start[1] >= maze[0].length || maze[start[0]][start[1]] == 1) {
    return false;
  }
  if (start[0] == end[0] && start[1] == end[1]) {
    path.push(start);
    return true;
  }
  maze[start[0]][start[1]] = 1;
  path.push(start);
  if (findPath(maze, [start[0]-1, start[1]], end, path) || findPath(maze, [start[0], start[1]+1], end, path) || findPath(maze, [start[0]+1, start[1]], end, path) || findPath(maze, [start[0], start[1]-1], end, path)) {
    return true;
  }
  path.pop();
  return false;
}

if (findPath(maze, start, end, path)) {
  console.log(JSON.stringify(path));
} else {
  console.log("No path found.");
}


for (let u=0;u<path.length;u++){
maze[path[u][0]][path[u][1]]="*";
}

for (let j=0;j<rows;j++) {
let s='';
for (let i=0;i<cols;i++) {
if (maze[j][i]==0){maze[j][i]="2"}
s+=maze[j][i];

}
console.log( `` + s + '    ' + Math.random());
}