Possible Duplicate:
How to split (chunk) a Ruby array into parts of X elements?
I would like to split an array into an array of sub-arrays.
For example,
big_array = (0...6).to_a
How can we cut this big array into an array of arrays (of a max length of 2 items) such as:
arrays = big_array.split_please(2)
Where...
arrays # => [ [0, 1],
[2, 3],
[4, 5] ]
Note: I ask this question, 'cause in order to do it, I'm currently coding like this:
arrays = [
big_array[0..1],
big_array[2..3],
big_array[4..5]
]
...which is so ugly. And very unmaintainable code, when big_array.length > 100
.
An efficient solution is to first find the sum S of all array elements. Check if this sum is divisible by 3 or not. This is because if sum is not divisible then the sum cannot be split in three equal sum sets. If there are three contiguous subarrays with equal sum, then sum of each subarray is S/3.
You can use the #each_slice
method on the array
big_array = (0..20).to_a
array = big_array.each_slice(2).to_a
puts array # [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11], [12, 13], [14, 15], [16, 17], [18, 19], [20]]
check out the slice:
big_array.each_slice( 2 ).to_a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With