Skip to content

Instantly share code, notes, and snippets.

@O-I
Created Sep 24, 2014
Embed
What would you like to do?
Nsect an array in Ruby
# nsect takes an array and optional positive integer n (default is 3)
# and returns the array partitioned into n arrays, (n-1) of which are
# of size i, the nth partition being of size (i-1), i, or (i+1).
# Examples below:
def nsect(arr, n = 3)
i = (arr.size + 1) / n
ans = []
(n-1).times do |j|
ans << arr[(0+j)*i...(1+j)*i]
end
ans << arr[(n-1)*i..-1]
end
p nsect([]) # => [[], [], []]
p nsect([*1..6]) # => [[1, 2], [3, 4], [5, 6]]
p nsect([*1..8]) # => [[1, 2, 3], [4, 5, 6], [7, 8]]
p nsect([*1..10]) # => [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
p nsect([*1..20], 5) # => [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]]]
p nsect([*1..20], 7) # => [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment