Skip to content

Instantly share code, notes, and snippets.

@O-I
Created September 24, 2014 17:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save O-I/df37c60842ab232c47a0 to your computer and use it in GitHub Desktop.
Save O-I/df37c60842ab232c47a0 to your computer and use it in GitHub Desktop.
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