Given an n x n array, write a method that returns the array elements arranged from outermost elements to the middle element, traveling clockwise.
A good way to visualize this is to picture the spiral shell of a snail!
const arrayMatrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
snail(arrayMatrix) #=> [1, 2, 3, 6, 9, 8, 7, 4, 5]
arrayMatrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
snail(arrayMatrix) #=> [1, 2, 3, 6, 9, 8, 7, 4, 5]
- Copy this markdown and paste in your own, private gist
- In your private gist, fill out the questions below
- Submit by the due time as instructed in Zoom
Do not publish your code on a public repl.it or repo or other public means.
What assumptions will you make about this problem if you cannot ask any more clarifying questions? What are your reasons for making those assumptions?
I would assume that this problem is in terms of a square. If the problem is nXn then it should have equal width and height.
I want to return the entire first array, then the last elements of all arrays (decending), then the bottom array backwards, then the first element of every array (acending). I want to continue this pattern until the entire set is consumed.
- Searching of Data
- Sorting of Data
- Pattern Recognition
- Build/Navigate a Grid
- Math
- Language API knowledge
- Optimization
I would probably start with sorting of data. I already described above the patern that I would use. Optimization would probably be last, although I would want to look at it if I had the time.
assign a variable to be returned
create a while loop to run while the matrix's length is greater than 0
push a spread of the matrix.shift to the variable (this returns the first index as individuals)
create a for loop that loops through the matrix's length
push the matrix's at index i's last element to the variable (var.push(matrix[i].pop()), this will return the last element of every nested array in decending order
push the last array in reverse to the variable
create another for loop that loops in reverse (let i=matrix.length; i>=0; i--) this is to loop back up the matrix
push the first element of each array in this loop. This gives the first number of each array in acending order
finally return the variable that has the unraveled matrix
function snail(matrix) {
let unraveledMatrix = [];
while(matrix.length) {
unraveledMatrix.push(...matrix.shift())
for(let i = 0; i < matrix.length; i++) {
unraveledMatrix.push(matrix[i].pop())
}
unraveledMatrix.push(...(matrix.pop() || []).reverse())
for(let i=matrix.length-1; i>=0; i--){
unraveledMatrix.push(matrix[i].shift())
}
}
return unraveledMatrix
}
I'm not 100% sure but I think this is o^n because it depends on the length of the matrix being passed in, but there are never any nested loops or iterators.