tags:

views:

213

answers:

3

Say I have an array that represents a set of points:

x = [2, 5, 8, 33, 58]

How do I generate an array of all the pairwise distances?

Thanks!

+4  A: 
x = [2, 5, 8, 33, 58]
print x.collect {|n| x.collect {|i| (n-i).abs}}.flatten

I think that would do it.

Lucas Oman
A: 

If you really do want an array instead of a matrix, this is O(n^2/2) instead of O(n^2).

result=[]
x.each_index{|i| (i+1).upto(x.size-1){|j| result<<(x[i]-x[j]).abs}}
AShelly
this is still O(n^2), but with half the number comparisons. O(n!) is not what you mean anyway.
David Nehme
Oops - If 4! is 4*3*2*1, what is 4+3+2+1 called?
AShelly
A: 
x.map{|i| x.map{|j| (i-j).abs } }

gives

[[0, 3, 6, 31, 56],
 [3, 0, 3, 28, 53],
 [6, 3, 0, 25, 50],
 [31, 28, 25, 0, 25],
 [56, 53, 50, 25, 0]]

(format it like this by printing it with 'pp' instead of puts)

and

x.map{|i| x.map{|j| (i-j).abs } }.flatten

gives

[0, 3, 6, 31, 56, 3, 0, 3, 28, 53, 6, 3, 0, 25, 50, 31, 28, 25, 0, 25, 56, 53, 50, 25, 0]

if you really want an array

webmat