2

I have to find an algorithm that can find the total amount of intersections between two sets of arrays, whereas one of the array is sorted.

An example, we have these two arrays and we draw straight lines towards corresponding number. Intersection Points

These two arrays gives us a total of 7 intersections.

What kind of algorithms does it exist to help me with this problem?

I have used the search button but did not find anything that would solve this problem for me.

Thanks

Jozo
  • 115
  • 1
  • 7
  • Are you trying to do this with maximum efficiency for arrays with millions of entries, or are the arrays small, e.g. 100 entries max? – user3386109 Dec 11 '16 at 08:51
  • 1
    Arrays are small, but the number of elements should not matter, i.e, I dont care about the efficiency. – Jozo Dec 11 '16 at 08:56

2 Answers2

1

Given two number M and N, the lines won't intersect if

  • the top M is to the right of the top N, and the bottom M is to the right of the bottom N
  • the top M is to the left of the top N, and the bottom M is to the left of the bottom N

In the other two cases:

  • left top, right bottom
  • right top, left bottom

the lines do intersect.

In the example, 8 is to the left of all 4 numbers on the top row, and to the right of 3 numbers on the bottom, so 8 intersects with three numbers.

5 is to the right of 8 on top, left of 8 on the bottom, giving one intersection. 5 is left of 4 and 1 on top, and right of 4 and 1 on the bottom, giving two more. So 5 intersects with three numbers.

Note that we counted the intersection of 5 and 8 twice. In fact every intersection will be counted twice. If you finish the example, you'll count 14 intersections. Divide by 2 at the end to get the answer.

user3386109
  • 34,287
  • 7
  • 49
  • 68
-1

you can represent each line as y=a+bx and then compare each line to the others by comparing their y values.

each line will have maximum one intersection with each other line.

  • Mind elaborating? Yes indeed, each line will have maximum one intersection with each line. What is a+bx in this case? The value of A at the index corresponding number? – Jozo Dec 11 '16 at 08:29
  • @Jozo a direct line is defined by the function ```y=a+bx``` you can read more here: https://en.wikipedia.org/wiki/Line_(geometry) – Shota Papiashvili Apr 09 '17 at 12:08