Created
September 26, 2019 18:18
-
-
Save dotspencer/151032486c48f4230a6eddd2524b03d3 to your computer and use it in GitHub Desktop.
Simple Maze Graph Generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(() => { | |
const dim = 7; | |
const graph = {}; | |
const path = []; | |
// create graph | |
for (let i = 0; i < dim*dim; i++) { | |
const row = i % dim; | |
const col = Math.floor(i / dim); | |
const edges = [ | |
getIndex(row + 1, col), | |
getIndex(row -1, col), | |
getIndex(row, col + 1), | |
getIndex(row, col - 1), | |
].filter(e => e != null); | |
graph[i] = { | |
edges: shuffle(edges), | |
}; | |
} | |
// create maze path | |
explore(graph, 0); | |
console.log('graph:', graph); | |
console.log('path:', path); | |
function getIndex(row, col) { | |
if (row >= dim || row < 0 || col >= dim || col < 0) return null; | |
return (col * dim) + row; | |
} | |
function shuffle(array) { | |
for(let i = 0; i < array.length; i++){ | |
const randomIndex = Math.floor(Math.random() * array.length); | |
const temp = array[i]; | |
array[i] = array[randomIndex]; | |
array[randomIndex] = temp; | |
} | |
return array; | |
} | |
function explore(graph, currentIndex) { | |
const current = graph[currentIndex]; | |
current.visited = true; | |
for (let i = 0; i < current.edges.length; i++) { | |
const nextIndex = current.edges[i]; | |
const next = graph[nextIndex]; | |
if (!next.visited) { | |
path.push([currentIndex, nextIndex]); | |
explore(graph, nextIndex); | |
} | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment