Last active
July 12, 2017 00:50
-
-
Save bingo347/fe06c57a848617bce288809604a24354 to your computer and use it in GitHub Desktop.
Transform matrix to spiral-path vector
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
'use strict'; | |
const LEFT = {i: -1, j: 0}; | |
const BOTTOM = {i: 0, j: 1}; | |
const RIGHT = {i: 1, j: 0}; | |
const TOP = {i: 0, j: -1}; | |
function* direction() { | |
var step = 0; | |
for(;;) { | |
step++; | |
yield {step, dir: LEFT}; | |
yield {step, dir: BOTTOM}; | |
step++; | |
yield {step, dir: RIGHT}; | |
yield {step, dir: TOP}; | |
} | |
} | |
function matrix2spiral(matrix) { | |
//check matrix | |
if(!Array.isArray(matrix)) { | |
throw new Error('Matrix must be array of arrays'); | |
} | |
if(matrix.length % 2 === 0) { | |
throw new Error('Incorrect matrix size'); | |
} | |
for(let i = matrix.length; i--;) { | |
if(!Array.isArray(matrix[i])) { | |
throw new Error('Matrix must be array of arrays'); | |
} | |
if(matrix.length !== matrix[i].length) { | |
throw new Error('Incorrect matrix size'); | |
} | |
} | |
//calculate spiral vector | |
const result = []; | |
var i, j; | |
i = j = (matrix.length - 1) / 2; | |
for(let {step, dir} of direction()) { | |
for(let k = step; k--;) { | |
result.push(matrix[j][i]); | |
if(i === 0 && j === 0) { | |
return result; | |
} | |
i += dir.i; | |
j += dir.j; | |
} | |
} | |
} | |
module.exports = matrix2spiral; |
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
#!/usr/bin/env node | |
'use strict'; | |
const matrix2spiral = require('./matrix2spiral.js'); | |
const N = parseInt(process.argv[2]); | |
if(isNaN(N)) { | |
console.log('Usage:\n./run.js N\n where N - integer'); | |
process.exit(1); | |
} | |
const matrix = genMatrix(N); | |
console.log('Matrix:\n' + matrix.map(row => row.join(' ')).join('\n') + '\n\n'); | |
const result = matrix2spiral(matrix); | |
console.log('Result:\n' + result.join(' ')); | |
function genMatrix(N) { | |
const len = 2 * N - 1; | |
const matrix = new Array(len); | |
for(let i = len; i--;) { | |
let row = matrix[i] = new Array(len); | |
for(let j = len; j--;) { | |
row[j] = Math.floor(Math.random() * 36).toString(36); | |
} | |
} | |
return matrix; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Установка и запуск:
./run.js N
, где N - целое число, основание для построения матрицы