Nested each_with_index Methods

Hey guys,

Just wondering if there is an easier way to write a nested each_with_index method than the solution I created. Is there any way to offset the value of “j” so there are no duplicate pairs? I did my research and each.with_index(1) and each.with_index(i + 1) do not solve the problem.

class Array

    def pair_sum(target)
      pairs = []
      self.each_with_index do |el1, i|
        self.each.with_index do |el2, j|
          if el1 + el2 == target
               pairs << [i, j] unless i == j || pairs.include?([j,i])
          end
        end
      end
      pairs
    end
  end

Btw this is from Advanced Debugging under Classes.

Thanks!

Hi Jackie,

There’s two options here:

def pair_sum(target)
  pairs = []
  self.each_with_index do |el1, i|
    self.each.with_index do |el2, j|
      next if j <= i
      if el1 + el2 == target
         pairs << [i, j] unless i == j || pairs.include?([j,i])
      end
    end
  end
  pairs
end
def pair_sum(target)
  pairs = []
  i = 0
  j = 1
  while i < self.length
    while j < self.length
      if self[i] + self[j] == target
         pairs << [i, j] unless i == j || pairs.include?([j,i])
      end
      j += 1
    end
    i += 1
    j = i + 1
  end
  pairs
end

Let me know if you have any questions about either option!

I’ve been enjoying creating a range of indices that occur ahead of my current index. it would look like this

self.each_with_index do |el, i|
          range = (i+1..self.length-1)
          range.each { |j| pairs << [i, j] if el + self(j) == target } 
 end

seems to work well so far. Any comment or suggestion is welcome of course