dimanche 28 juin 2015

Give array elements unique IDs

I am trying to multiply every element in an array by the next 12 elements:

array.each do |n|
    a = array.index(n)
    b = a + 12
    product = 1
    array[a..b].each { |i| product *= i }
    highest = product if product > highest
end

I run into a problem when there are multiple occurrences of the same integer in the array:

[1, 2, 3, 7, 5, 4, 7] # this is not the actual array

When the second 7 runs through my block, its array.index(n) becomes 3 (the index of the first 7) when I want it to be 6 (the index of the particular 7 I am working with). I'm pretty sure this can be solved by giving each element of the array a unique 'id', but I'm not sure how I would go about doing this.

My question is, how do I give every element in an array a unique id? The Array#uniq method is not what I am looking for.

Aucun commentaire:

Enregistrer un commentaire