xamples
epeat
ode
pproach
ptimize
est
console.log(spiral(array));
//[0,1,2,3,4,9,14,19,18,17,16,15,10,5,6,7,8,13,12,11];
Note: The subarrays in the input array are always of equal length.
var array =
[[0,1,2,3,4],
[5,6,7,8, 9],
[10,11,12,13,14],
[15,16,17,18,19]];
[[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
[[10]]
[[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
[[5,6,7],
[9,10,11],
[13,14,15]]
[[5,6,7],
[9,10,11],
[15,14,13]]
[[5,6,7],
[9,10,11]]
[[6,7],
[10,11]]
[[10,11]]
function spiral(array) {
let result = [];
while (array.length) {
// Steal the first row.
result = result.concat(array.shift());
// Steal the right items.
for (var i = 0; i < array.length; i++) result.push(array[i].pop());
// Steal the bottom row.
result = result.concat((array.pop() || []).reverse());
// Steal the left items.
for (var i = array.length - 1; i >= 0; i--) result.push(array[i].shift());
}
return result;
}
let array = [[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]];
[1,2,3,4]
[5,6,7,8],
[9,10,11,12],
[13,14,15,16] ----> [8, 12, 16]
[7, 11, 15]
[6,10,14]
[5,9,13] [1,2,3,4,8,12,16]
(return first array and do the
same thing with the remaining
elements) ----------------------> [15,14,13] [1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]
[11,10,9]
[7,6,5] -----------> [9,5]
[10,6]
[11,7] --> [6,7]
[10,11] --> [10,11]
function spiral(array) {
//if the array has a length of 0 or 1, return array
if(!array.length) {
return;
} else if (array.length === 1) {
return array[0]; //assuming multi-dim array
}
let firstRow = array[0],
numRows = array.length,
nextRows = [],
newArr,
rowIndex,
colIndex = array[1].length - 1;
//store elements in new arrays to push into the next row
for(colIndex; colIndex >= 0; colIndex--) {
newArr = [];
for(rowIndex = 1; rowIndex < numRows; rowIndex++) {
newArr.push( array[rowIndex][colIndex]);
}
nextRows.push( newArr );
}
firstRow.push.apply( firstRow, spiral(nextRows));
return firstRow;
}
function getSpiralElements(input) {
var results = [ ];
var limit = 20;
function getSpiralHelper(multiDimArr) {
if (multiDimArr.length === 1 || multiDimArr.length === 0) {
if (multiDimArr[0] && multiDimArr[0].length) {
results = results.concat(multiDimArr[0]);
}
return;
}
results = results.concat(multiDimArr.shift());
multiDimArr.forEach(function(subArray) {
results = results.concat(subArray.pop());
});
multiDimArr = multiDimArr.reverse();
multiDimArr.forEach( function (el, index, arr) {
arr[index] = el.reverse();
});
return getSpiralHelper(multiDimArr);
}
var valid = true;
input.forEach(function (el) {
if (el instanceof Array === false )
valid = false;
});
if (!valid) throw new TypeError("Input should be an array of arrays!")
getSpiralHelper(input);
return results;
}
Think about how to break up a problem into smaller pieces and just start tackling those smaller pieces.