Skip to content

Instantly share code, notes, and snippets.

@bingo347
Last active July 12, 2017 00:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bingo347/fe06c57a848617bce288809604a24354 to your computer and use it in GitHub Desktop.
Save bingo347/fe06c57a848617bce288809604a24354 to your computer and use it in GitHub Desktop.
Transform matrix to spiral-path vector
'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;
#!/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;
}
@bingo347
Copy link
Author

Задача:
Есть матрица 2n-1 x 2n-1, заполненная случайными значениями.
Надо вывести их на экран в ряд, начиная из центра по спирали: влево - вниз - вправо - вверх и т.д.

Пример

Если матрица:
1 2 3
4 5 6
7 8 9

То результат:
5 4 7 8 9 6 3 2 1

Установка и запуск:

  1. Необходимо node.js 6.0+ (тестировалось на node.js 8.1.4), основной модуль можно запускать в любом es2015 совместимом окружении
  2. Склонировать этот gist
  3. Запустить: ./run.js N, где N - целое число, основание для построения матрицы

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment