Created
December 18, 2009 19:48
-
-
Save arnab/259715 to your computer and use it in GitHub Desktop.
This file contains 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
def columnize(arr, columns) | |
size_in_group = arr.size / columns | |
if arr.size % columns != 0 | |
size_in_group += 1 | |
end | |
arr_grouped = [ ] | |
size_in_group.times do |m| | |
columns.times do |i| | |
arr_grouped[i] ||= [] | |
arr_grouped[i] << arr[m * columns + i] | |
end | |
end | |
arr_grouped | |
end | |
# Examples: | |
require "pp" | |
# Input: a..z, columns: 2 | |
# call: | |
pp columnize(('a'..'z').to_a, 2) | |
# Output: | |
[ | |
["a", "c", "e", "g", "i", "k", "m", "o", "q", "s", "u", "w", "y"], | |
["b", "d", "f", "h", "j", "l", "n", "p", "r", "t", "v", "x", "z"] | |
] | |
# Input: a..z, columns: 3 | |
# call: | |
pp columnize(('a'..'z').to_a, 3) | |
# Output: | |
[ | |
["a", "d", "g", "j", "m", "p", "s", "v", "y"], | |
["b", "e", "h", "k", "n", "q", "t", "w", "z"], | |
["c", "f", "i", "l", "o", "r", "u", "x", nil] | |
] | |
# Note that the last elem in the 3rd array is nil | |
# Input: a..z, columns: 3 | |
# call: | |
pp columnize(('a'..'x').to_a, 3) | |
# Output: | |
[ | |
["a", "d", "g", "j", "m", "p", "s", "v"], | |
["b", "e", "h", "k", "n", "q", "t", "w"], | |
["c", "f", "i", "l", "o", "r", "u", "x"] | |
] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment