Created
February 7, 2019 17:26
-
-
Save snewcomer/ff55be699f458e16661e8e6fce9c20b7 to your computer and use it in GitHub Desktop.
spiral-algorithm
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
let arrayOfApps = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]; | |
const N = [0, -1]; | |
const E = [1, 0]; | |
const S = [0, 1]; | |
const W = [-1, 0]; | |
const EMPTY = `~EMPTY_SIGIL~` | |
let directions = { N, E, S, W }; | |
let r_directions = { 'N': 'E', 'E': 'S', 'S': 'W', 'W': 'N' }; | |
let rows = 5; | |
let columns = 5; | |
// initial 1/2 point | |
let x = columns + 1 >> 1 | |
let y = rows + 1 >> 1; | |
let dir = 'N'; | |
let [dx, dy] = directions[dir]; | |
let grid = createGrid(rows, columns); | |
let result = fillInGrid(grid, x, y); | |
// ***** | |
//====== RESULT | |
// ***** | |
console.log(result) | |
function fillInGrid(grid, x, y) { | |
while (true) { | |
grid[x-1][y-1] = arrayOfApps.shift(); | |
// turn right if not visited | |
let new_dir = r_directions[dir]; | |
let [new_dx, new_dy] = directions[new_dir]; | |
let new_x = x + new_dx; | |
let new_y = y + new_dy; | |
if (isInBounds(x, y) && grid[new_x-1][new_y-1] === EMPTY) { | |
// turn right and continue | |
x = new_x; | |
y = new_y; | |
dx = new_dx; | |
dy = new_dy; | |
dir = new_dir; | |
} else { | |
// just keep going in the direction you were headed, maybe continue | |
x = x + dx; | |
y = y + dy; | |
if (!isInBounds(x, y)) { | |
// nowhere to go. Just return | |
return grid; | |
} | |
} | |
} | |
} | |
function isInBounds(x, y) { | |
return (x >= 0 && x <= columns) && (y >= 0 && y <= rows); | |
} | |
function createGrid(w, h) { | |
let arr = Array(w).fill(0).map((num, indx) => num + indx); | |
return arr.map((x) => { | |
return arr.reduce((acc, y) => { | |
return acc.concat([EMPTY]) | |
}, []) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment