Home > Back-end >  Find the difference between all integers in an array
Find the difference between all integers in an array

Time:08-03

I have an array of integers in Ruby. I want to find the difference between all of them. I can do it with one of the integers and find the difference between it and all the other numbers but I can't work out how to iterate twice per se.

Here is what I have:

def stock_picker ary
  sub = ary.map {|a| ary[0]-a }
  puts sub
end

stock_picker [1, 2, 3, 4, 5]

The result from this is

0
-1
-2
-3
-4

I want to do the same thing for every index, not just ary[0] but all of the numbers for however long the array is. The output I want is:

0 -1 -2 -3 -4 1 0 -1 -2 -3 2 1 0 -1 -2 3 2 1 0 -1 4 3 2 1 0

There is likely a better way. I am a novice hoping to learn! Thanks for any help.

CodePudding user response:

More compact version:

arr.product(arr).map { |a,b| a - b }

CodePudding user response:

It appears you want the following.

def doit(arr)
  arr.flat_map { |n| arr.map { |m| n-m } }
end
doit [1, 2, 3, 4, 5]
  #=> [0, -1, -2, -3, -4, 1, 0, -1, -2, -3, 2, 1,
  #    0, -1, -2, 3, 2, 1, 0, -1, 4, 3, 2, 1, 0]

See Enumerable#flat_map.

  • Related