Each_Slice on arrays in Ruby

I hope to get a nested array containing separate arrays that contain at least three elements but no more than four elements. I run into a problem when I get to 10:

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

example.each_slice(3).to_a = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
example.each_slice(4).to_a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]

Desired Result:

[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]       (all arrays have 3 elements but no more than 4)

Does every_slice seem like no way to do this?

thank

+4
source share
2 answers

each_slice slices to the desired size; it will not directly do what you want here, which is a kind of "balancing" of the list. Fortunately, we can get there.

list = (1..10).to_a
slice_count = (list.length / 3.0).floor
list.each_slice(slice_count).to_a.each {|l| l.fill nil, slice_count, 0 }.transpose.map(&:compact)
# => [[1, 4, 7, 10], [2, 5, 8], [3, 6, 9]]

, . , , , , , .

1  2  3
4  5  6
7  8  9
10 -  -

#transpose , nils.

. 3/4 .

+2

, , , , .

def divide_up(arr)
  sz = arr.size
  return nil if [0,1,2,5].include?(sz)
  n3, d = sz.divmod(3)
  return arr.each_slice(3).to_a if d.zero?
  return arr.each_slice(4).to_a if d==n3
  n3 -= d
  arr[0,3*n3].each_slice(3).to_a + arr[3*n3..-1].each_slice(4).to_a
end

d==n3 (d==1 && n3==1) || (d==2 && n3==2).

< >

16.times do |n|
  arr = [*1..n]
  puts "for: #{arr}:"
  a=divide_up(arr)
  puts "  #{(a ? a : "No solution")}"
end
  #=> for: []:
  #     No solution
  #   for: [1]:
  #     No solution
  #   for: [1, 2]:
  #     No solution
  #   for: [1, 2, 3]:
  #     [[1, 2, 3]]
  #   for: [1, 2, 3, 4]:
  #     [[1, 2, 3, 4]]
  #   for: [1, 2, 3, 4, 5]:
  #     No solution
  #   for: [1, 2, 3, 4, 5, 6]:
  #     [[1, 2, 3], [4, 5, 6]]
  #   for: [1, 2, 3, 4, 5, 6, 7]:
  #     [[1, 2, 3], [4, 5, 6, 7]]
  #   for: [1, 2, 3, 4, 5, 6, 7, 8]:
  #     [[1, 2, 3, 4], [5, 6, 7, 8]]
  #   for: [1, 2, 3, 4, 5, 6, 7, 8, 9]:
  #     [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  #   for: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
  #     [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
  #   for: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]:
  #     [[1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
  #   for: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]:
  #     [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
  #   for: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]:
  #     [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12, 13]]
  #   for: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]:
  #     [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10], [11, 12, 13, 14]]
  #   for: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]:
  #     [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]]
+1

All Articles