Last active
August 29, 2015 14:26
-
-
Save kangkyu/0d7872678b9d1c35ac17 to your computer and use it in GitHub Desktop.
Thanks to Charlie, this is great for us to have 15-minute code kata every weekday .
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# write a method called "transpose" that takes this array of arrays: | |
# [ | |
# ['first', 'second'], | |
# ['third', 'fourth'] | |
# ] | |
# and transposes it into this array of arrays | |
# [ | |
# ['first', 'third'], | |
# ['second', 'fourth'] | |
# ] | |
# you can think of it as rows become columns | |
# I know there is an Array method called "transpose" but | |
# I am asking you to write your own | |
def transpose(before) | |
before_row_count = before.count | |
before_col_count = before[0].count | |
after = Array.new(before_col_count, []) | |
(0...before_row_count).each do |i| | |
(0...before_col_count).each do |j| | |
after[j][i] = before[i][j] | |
end | |
end | |
after | |
end | |
puts transpose([ | |
['first', 'second'], | |
['third', 'fourth'] | |
] | |
).inspect | |
# [["first", "third"], ["second", "fourth"]] | |
puts transpose([ | |
['0-0', '0-1', '0-2'], | |
['1-0', '1-1', '1-2'] | |
] | |
).inspect | |
# [["0-0", "1-0"], ["0-1", "1-1"], ["0-2", "1-2"]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment