JSFiddle - React, Tailwind, and code Playground
JavaScript
"use strict";
function run(input, result) {
result = result || []
if (input.length == 0) {
return result;
}
if (input.length === 1) {
result.push(input[0][0])
return result
}
result = result.concat(input.shift());
input.forEach(function(rightEnd) {
result.push(rightEnd.pop());
});
result = result.concat(input.pop().reverse());
var tmp = [];
input.forEach(function(leftEnd) {
tmp.push(leftEnd.shift());
});
result = result.concat(tmp.reverse());
return run(input, result);
}
console.log(
'3x3',
run(
[[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]]
)
)
console.log(
'4x4',
run(
[[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
)
);