Total amount of time covered by the intervals

There’s a room with a TV and people are coming in and out to watch it. The TV is on only when there’s at least a person in the room. For each person that comes in, we record the start and end time. We want to know for how long the TV has been on. In other words, given a list of arrays of time intervals, write a function that calculates the total amount of time covered by the intervals.

For example:
input = [(1,4), (2,3)]
output = 3
input = [(4,6), (1,2)]
output = 3
input = [(1,4), (6,8), (2,4), (7,9), (10, 15)]
output = 11

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numArray = { 1, 4, 6, 8, 2, 4, 7, 9, 10, 15 };
            //Sort the array based on starting point
            numArray = BubbleSort(numArray);
            ArrayList numArrayList = new ArrayList();
            numArrayList.AddRange(numArray);
            for (int i = 1; i = (int)numArrayList[i + 1]) && ((int)numArrayList[i] = (int)numArrayList[i + 1]) && ((int)numArrayList[i] >= (int)numArrayList[i + 2]))
                {
                    numArrayList.RemoveAt(i + 1);
                    numArrayList.RemoveAt(i + 1);
                    i = i - 2;
                }
            }
            int totalTime = 0;
            for (int i = 0; i < numArrayList.Count - 1; i = i + 2)
            {
                totalTime = totalTime + ((int)numArrayList[i + 1] - (int)numArrayList[i]);
            }
            Console.WriteLine("Total time covered = " + totalTime);
        }

        public static int[] BubbleSort(int[] numArray)
        {
            int temp1, temp2;
            for (int pass = 0; pass <= numArray.Length - 4; pass++)
            {
                for (int i = 0; i  numArray[i + 2])
                    {
                        temp1 = numArray[i];
                        temp2 = numArray[i + 1];
                        numArray[i] = numArray[i + 2];
                        numArray[i + 1] = numArray[i + 3];
                        numArray[i + 2] = temp1;
                        numArray[i + 3] = temp2;
                    }
                }
            }
            return numArray;
        }
    }
}

Output
=======
Total time covered = 11
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