JavaScript

Задачка на мышление. JavaScript. Вращение массива

Приветствую. Есть задачка, сам что-то ничего простого не могу придумать.
Есть матрица:
[0,1,0]
[1,1,1]

Необходимо по нажатию кнопки ее вращать, то есть:
[0,1]
[1,1]
[0,1]
Следующее нажатие:
[1,1,1]
[0,1,0]
Еще раз:
[1,0]
[1,1]
[1,0]

То есть просто вращать против часовой.

Вот что у меня уже получилось:
codepen.io/anon/pen/eRmEXV?editors=0010
Игорь Иванов
Игорь Иванов
3 120
function result(matrix) {
let res = "";
for (let row of matrix) {
for (let value of row) {
res += value + " ";
}
res += "\n";
}
return res;
}

function rotate(matrix) {
let result = [];
while (matrix[0].length) {
let tmp = [];
for (let row of matrix) {
tmp.push(row.pop());
}
result.push(tmp);
}
return result;
}

let matrix = [[0, 1, 0], [1, 1, 1]];
let res = result(matrix);
console.log(res);
matrix = rotate(matrix);
res = result(matrix);
console.log(res);
matrix = rotate(matrix);
res = result(matrix);
console.log(res);
matrix = rotate(matrix);
res = result(matrix);
console.log(res);
matrix = rotate(matrix);
res = result(matrix);
console.log(res);
АД
Аскар Даулеткалиев
58 303
Лучший ответ
Игорь Иванов Гениально, спасибо!
Просто меняешь x с y местами...
Изящно и без единого костыля:

var matrix = [
[0,1,0],
[1,1,1]
], newMatrix=[];

function rotateMatrix (m) {
var tmpMatrix=[];
document.getElementById('mtx').innerHTML='';
for (var i=0, L=m.length; i < L; i++) {
for (var j=0, L1=m[0].length; j < L1; j++) {
//for (var j=m[0].length-1; j >=0; j--) {
tmpMatrix[j]=tmpMatrix[j] || [];
tmpMatrix[j][i]= m[i][L1-1-j];
document.getElementById('mtx').innerHTML+=m[i][j]+' ';
};
document.getElementById('mtx').innerHTML+='';
};
newMatrix=tmpMatrix;
}

rotateMatrix(matrix);
МM
Макс_ Maks
8 942
Макс_ Maks var matrix = [
[0,1,0],
[1,1,1]
], newMatrix=[];

function rotateMatrix (m) {
var tmpMatrix=[];
document.getElementById('mtx').innerHTML='';
for (var i=0, L=m.length; i < L; i++) {
for (var j=0, L1=m[0].length; j < L1; j++) {
tmpMatrix[j]=tmpMatrix[j] || [];
tmpMatrix[j][i]= m[i][j];
document.getElementById('mtx').innerHTML+=m[i][j]+' ';
};
document.getElementById('mtx').innerHTML+='';
};
newMatrix=tmpMatrix;
}

rotateMatrix(matrix);
полный код с примерами (повороты влево и вправо) - https://repl.it/I7Zj

class Matrix {
constructor(state) {
this.state = state;

}

nextMatrixItem(i) {
return this.state.map(x => x[i]);
}

rotate(direction) {

const nextMatrixLen = this.state[0].length; // длина новой матрицы

if(direction === 'right') this.state = this.state.reverse();

this.state = Array(nextMatrixLen)
.fill()
.map((_, i) =>
this.nextMatrixItem(direction === 'left' ? (nextMatrixLen - 1) - i : i));

return this.state;
}

rotateOneTurn(direction) {
Array(4).fill().map((_, i) => console.log(this.rotate(direction)));
}

}
RB
Rashid Bektemirov
2 554
Наверное, вращать (перестраивать) матрицу смысла нет. Лучше изменять индексы. Если изначально к ячейке матрицы можно обратиться как к Cell(row, col), row = 0..1, col = 0..2, то потом Cell(col, row), row = 0..1, col = 0..2, Cell(row, col), row = 1..0, col = 2..0, Cell(col, row), row = 1..0, col = 2..0.
Andrey Vladimirovich
Andrey Vladimirovich
322
не задачка на мышление, а гавно для дебила.
в задачках на мышление уточняется тип мышления, на который эта задачка. впрочем, о чем я -
психолога же не пригласили, когда задач сочиняли. ну тогда хотя бы область, например: Длинная арифметика.
Игорь Иванов Я так понимаю ты не дебил, чтобы такое гавно решать? Удобно