Given a 2D array of m x n dimension, how can I loop through them in anti-clockwise fashion?
For example:
matrix = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ]]1st loop: 1, 5, 9, 13, 14, 15, 16, 12, 8, 4, 3, 22nd loop: 6, 10, 11, 7, 6
I really don't mind if the implementation is given in ruby or js
My current solution is like this:
(1..rotate).each do bottom_left_corner = i top_right_corner = j start_nth_layer = 1; end_nth_layer = matrix.length - 2 matrix.reverse_each do matrix[bottom_left_corner].unshift(matrix[bottom_left_corner - 1].shift) if bottom_left_corner > 0 matrix[top_right_corner] << matrix[top_right_corner + 1].pop if top_right_corner < matrix.length - 1 bottom_left_corner -= 1; top_right_corner += 1 end nth_layer(matrix, start_nth_layer, end_nth_layer) end
Update
The output doesn't format doesn't matter, as long as it outputs the correct order.
Purpose of the problem
The purpose of this problem is traverse these arrays anti-clockwise, layer by layer, until no more layers. For each traversal, we shift the values in anti-clockwise. For example:
Iteration 1: Iteration 2: Iteration 3: ============== ============= ============== 1 2 3 4 2 3 4 8 3 4 8 12 5 6 7 8 1 7 11 12 2 11 10 16 9 10 11 12 => 5 6 10 16 => 1 7 6 15 13 14 15 16 9 13 14 15 5 9 13 14