Splitting an array into arrays x

I have an array:

arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

      

I want to split arr1

into x slices where each slice is as complete and equal as possible.

arr2  = arr1.foo(3)
# => [1, 2, 3, 4][5, 6, 7][8, 9, 10]

      

each_slice

does the opposite of what I want, separating the array from groups of x elements.

arr2 = arr1.each_slice(3)
# => [1, 2, 3][4, 5, 6][7, 8, 9][10]

      

If possible, I want to do this without using special methods like in_groups

.

+3


source to share


3 answers


class Array
  def in_groups(n)
    len, rem = count.divmod(n)
    (0...n).map { | i | (i < rem) ? self[(len+1) * i, len + 1] : self[len * i + rem, len] }
  end
end

      



+6


source


Another approach:



def in_groups(array, n)
  a = array.dup
  n.downto(1).map { |i| a.pop(a.size / i) }.reverse
end

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

in_groups(arr, 1) #=> [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]
in_groups(arr, 2) #=> [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
in_groups(arr, 3) #=> [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
in_groups(arr, 4) #=> [[1, 2, 3], [4, 5, 6], [7, 8], [9, 10]]
in_groups(arr, 5) #=> [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]

      

+4


source


You can use recursion:

def in_groups(arr, n)
  return [arr] if n == 1
  len = arr.size/n
  [arr[0,len]].concat in_groups(arr[len..-1], n-1)
end

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

in_groups(arr,  1) #=> [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]] 
in_groups(arr,  2) #=> [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] 
in_groups(arr,  3) #=> [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]] 
in_groups(arr,  4) #=> [[1, 2], [3, 4], [5, 6, 7], [8, 9, 10]] 
in_groups(arr,  5) #=> [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] 
in_groups(arr,  9) #=> [[1], [2], [3], [4], [5], [6], [7], [8], [9, 10]] 
in_groups(arr, 10) #=> [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]] 
in_groups(arr, 11) #=> [[], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10]] 

      

Edit 1: first for the largest groups, click on .reverse

or replace the antepult line like this:

len = (arr.size.to_f/n).ceil

      

Edit 2: Below is a small variation on @undur's answer, maybe easier to follow for those with "B" and "C" brain types:

class Array
  def in_groups(n)
    size_small, nbr_large = count.divmod(n)
    size_large, nbr_small = size_small+1, n-nbr_large
    nbr_for_large = nbr_large * size_large  
    self[0, nbr_for_large].each_slice(size_large).to_a.concat(
      self[nbr_for_large..-1].each_slice(size_small).to_a)
  end
end

(1..10).to_a.in_groups(3)
  #=> [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]] 

      

+3


source







All Articles