Created
January 7, 2016 03:42
-
-
Save thinkdevcode/b107559828ad86219822 to your computer and use it in GitHub Desktop.
spirals, how do they work?
This file contains 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
"use strict"; | |
let directions = [[-1,0], [0,1], [1,0], [0,-1]]; | |
function spiral(n) { | |
let matrix = [], total = n * n; | |
let x = 0, y = 0, val = 1; | |
/// initialize matrix | |
for (let i = 0; i < n; i++) | |
matrix[i] = new Array(n); | |
/// get center | |
if (n % 2 !== 0) | |
x = y = Math.floor(n / 2); | |
else { | |
x = (n / 2) ; | |
y = (n / 2) - 1; | |
} | |
let path = generatePath(n); | |
/// step thru matrix | |
for (let step = 1, pindex = 0; step <= total; step++, pindex++) { | |
if (val % 10 === 0) | |
val = 0; | |
matrix[x][y] = val; | |
if (pindex < total - 1) { | |
x += directions[path[pindex]][0]; | |
y += directions[path[pindex]][1]; | |
} | |
val += 1; | |
} | |
return matrix; | |
} | |
function generatePath(n) { | |
let steps = [], | |
path = [], | |
count = 0; | |
for (let i = 0, val = 1; i <= (n*2-3); i += 2, val++) | |
steps[i] = steps[i+1] = val; | |
steps[steps.length] = (n - 1); // add a final leg | |
steps.forEach((step) => { | |
for (let i = 0; i < step; i++) path.push(count); // go for x amount of steps | |
count += 1; // make a turn | |
if (count % 4 === 0) count = 0; // reset count (only 4 directions) | |
}); | |
return path; | |
} | |
let kek = spiral(5); | |
kek.forEach((row) => { console.log(row); }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment