Created
September 24, 2014 17:26
-
-
Save O-I/df37c60842ab232c47a0 to your computer and use it in GitHub Desktop.
Nsect an array in Ruby
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
# 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