0

Lets say I have this data set...

var a = [5,6,7]; var b = [9,8,6];

Imagine that those values were plotted the y in a (x,y) coordinate pair, and the x was the array index, how could I tell if my two arrays had crossed at one point.

Thanks.

Gabe
  • 84,912
  • 12
  • 139
  • 238
Jeff
  • 873
  • 2
  • 10
  • 16

1 Answers1

1

Try this:

if ((a[0] < b[0]) == (a[1] > b[1]) ||
    (a[1] < b[1]) == (a[2] > b[2]))
{
    // crossed
}

The important point is that for some index i the values of a[i] is (greater|less) than b[i], and the relationship between a[i + 1] and b[i + 1] is the opposite.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • For larger data sets this method could start looking unwieldy. I think more intuitively just iterate over the arrays and do a[i]-b[i]>0. This should be true for all or false for all if they don't cross. If its true for some and not for others then they cross. You might also want to check for equality in case the arrays touch but do not cross (eg 3,2,3 and 1,2,1). – Chris Dec 30 '10 at 12:08