Pregunta

Ok started over, apologies for my verbose and poorly structured original post.

My question is basically this: is it possible to take an array of arrays and divide it into three equal-ish parts, sending each part to a hash where there are three key value pairs as described below?

Sample input: an array of arrays like:

orig_array = [[13, 11, 19, 17, 12, 5, 3], [3, 9, 2, 20], [5, 21, 15, 4], 
[18, 14, 16, 10], [6, 1, 8, 7], [15, 4, 17, 6], [3, 19, 13, 14], [9, 21, 12, 7], 
[20, 11, 2, 18], [8, 10, 1, 16], [10, 6, 21, 17], [15, 11, 14, 19], [13, 2, 9, 18], 
[5, 12, 16, 7], [20, 4, 1,8]]

Desired output: a hash where each key is a number starting with 1 and counting up, and each value is one third of the array, like:

hash = { 1=>[[array of arrays containing first 1/3rd elements from orig_array]], 
         2=>[[array of arrays containing next 1/3rd elements from orig_array]]
         3=>[[array of arrays containing next 1/3rd remaining elements from orig_array]]}

To be clear, this is part of an exercise for a class. The exercise is not to find a way to divide an array of arrays like this, I just feel like doing so could be part of one potential solution and am looking for guidance. Thanks!

¿Fue útil?

Solución

def unique_group_of_three(array)    
    multiple = array.size / 3
    return "Your collection is too small" if multiple < 5
    multiples = [multiple, multiple *2]
    array = array.shuffle

    {
        :first => array[0...multiple].uniq,
        :second => array[multiple...multiples[1]].uniq, 
        :third => array[multiples[1]..-1]].uniq
    }
end
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top