Match the rows

Count the number of line intersections while matching numbers across two rows. Assume that there won’t be a case wherein a line would intersect at more than two points.
Examples:

Number of intersections = 4


Number of intersections = 2


Number of intersections = 2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numArray1 = { 1, 2, 3, 4 };
            int[] numArray2 = { 3, 4, 1, 2 };
            int[] pathTracker = new int[numArray1.Length];
            //Initializing the path tracker array to 0
            for (int i = 0; i < pathTracker.Length; i++)
            {
                pathTracker[i] = 0;
            }
            int numberOfIntersections = 0;
            for (int i = 0; i < numArray1.Length; i++)
            {
                int j;
                for (j = 0; j < numArray2.Length; j++)
                {
                    if (numArray1[i] == numArray2[j])
                    {
                        break;
                    }
                }

                if (i <= j)
                {
                    for (int k = i; k < j; k++)
                    {
                        if (k != i && pathTracker[k] != 0)
                        {
                            numberOfIntersections++;
                        }
                        pathTracker[k] = 1;
                    }
                }
                else
                {
                    for (int k = i; k >= j; k--)
                    {
                        if (k != i && pathTracker[k] != 0)
                        {
                            numberOfIntersections++;
                        }
                        pathTracker[k] = 1;
                    }
                }
            }
            Console.WriteLine("Number of intersections = " + numberOfIntersections);
        }
    }
}
Output
=======
Number of intersections = 4
Press any key to continue . . .
Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s