ruby - Get original array indices after #combination -


i learning ruby , 1 issue have come across in few practice problems working combinations array, getting original array indices instead of actual combination result. keep simple let's talk pairs. know fast way possible pairs is:

array = [a, b, c] array.combination(2).to_a    # => [[a, b], [a, c], [b, c]] 

now let's want iterate on these combinations , choose pair fits arbitrary condition. easy enough return pair itself:

...select{|pair| condition} # => [a, c]  # assuming pair fits condition 

but if want return indices original array instead?

# => [0, 2] 

is there way of doing using #combination ? or have find combinations in case? if there more elegant way following(which ended doing solve these problems)?

array.each.with_index |s1, i1|  array[(i1 + 1)..-1].each.with_index |s2, i2|   if condition     result = [i1, (i2 + i1 + 1)]   end  end end 

try this:

array = ['a', 'b', 'c', 'd'] array.combination(s).to_a.reduce |memo, pair|   if condition  # tested pair[0] == 'a' && pair[1] == 'c'     memo = pair.map {|e| array.index(e)}   else     memo   end end 

my test of yielded:

[0, 2] 

edit

to avoid using call index, compute indexes ahead of time , create combination of them, selecting one(s) meet condition:

(0..array.length).to_a.combination(2).to_a.select {|pair| condition} 

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -