-
Notifications
You must be signed in to change notification settings - Fork 1
/
Ruby - rotateArrayMatrix.txt
61 lines (37 loc) · 2.12 KB
/
Ruby - rotateArrayMatrix.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
Write a rotate function that rotates a two-dimensional array (a matrix) either clockwise or anti-clockwise by 90 degrees, and returns the rotated array.
The function accepts two parameters: an array, and a string specifying the direction or rotation. The direction will be either "clockwise" or "counter-clockwise".
- - - - - - - my answer (updated for non-square matrix) - - - - - - -
def rotate matrix, direction
newMatrix, finalMatrix, i = [], [], 0
(matrix.length > matrix[0].length ? matrix.length : matrix[0].length).times do
matrix.map { |row| row[i] != nil ? newMatrix << row[i] : nil }
i+=1
end
direction == 'clockwise' ? newMatrix.each_slice(matrix.length).to_a.map { |newRow| newRow.reverse} : newMatrix.each_slice(matrix.length).to_a.reverse
end
- start with initializing two empty arrays and an index-counter
- a number of times (which ever is bigger (columns or rows)), do the following:
- each pass through will only look at index ‘0’ or ‘1’ or ‘2’ ... etc pushing those items in sequentially.
- if the value does not equal ‘nil’ (which would occur because the matrix had more rows than columns), push the value into newMatrix.
- increment ‘i’ up one with each complete pass.
^^^ (this has the function of switching ‘rows’ with ‘columns’) ^^^
- if direction was ‘clockwise’ the answer array needs to be broken up into the original size rows (using ‘.each_slice’)
- then reverse each row-array to correctly position each element
- else if direction was ‘counter-clockwise’ we reverse the position of each row.
- - - alt - - -
def rotate matrix, direction
case direction
when 'clockwise'
matrix.transpose.map(&:reverse)
when 'counter-clockwise'
matrix.transpose.reverse
end
end
- - - alt - - -
def rotate matrix, direction
direction == "clockwise" ? matrix.transpose.map {|e| e.reverse} : matrix.transpose.reverse
end
- ‘.transpose’ takes in an array of arrays and swaps the rows and columns. essentially the top 4 lines of my code.
- then reverse either the columns within each row
- or the order of whole rows
- done and done