Lucas
Lucas

Reputation: 55

Another efficient way to write a nested "for" in ruby?

I have an exercise from HackerRank, that can easy resolve as the follow:

def divisibleSumPairs(n, k, ar)
  validPairs = 0
  for i in 0..ar.size-1
    for j in i+1..ar.size-1
      validPairs += 1 if (ar[i]+ar[j]) % k == 0
    end
  end
  validPairs
end

n, k = gets.strip.split(' ')
n = n.to_i
k = k.to_i
ar = gets.strip
ar = ar.split(' ').map(&:to_i)
result = divisibleSumPairs(n, k, ar)
puts result;

But that nested for is bothering me. Is there any other way to do that in Ruby?

Upvotes: 0

Views: 68

Answers (1)

katafrakt
katafrakt

Reputation: 2488

Yes. You can use combination method from Array class:

a = [1,2,3,4,5]
a.combination(2).to_a #=> [[1, 2], [1, 3], [1, 4], [1, 5], [2, 3], [2, 4], [2, 5], [3, 4], [3, 5], [4, 5]]

Then you can iterate on those pairs, so the code should look like that (haven't run it, though):

def divisibleSumPairs(n, k, ar)
  validPairs = 0
  ar.combination(2).each do |pair|
    validPairs += 1 if (pair[0]+pair[1]) % k == 0
  end
  validPairs
end

Upvotes: 2

Related Questions