Write a Program to Create a Two Dimensional Array From a Text File

Today we will write a program for creating a two dimensional Array from a input file.

Steps.

  1. Read input File.
  2. Calculate the row and column count.
  3. Read File line by line, split line by given delimiter and create two dimensional array.

C# Code

        public static int[,] Create2DMatrixFromFile(string inputFile
, char columnDelimiter) { if (File.Exists(@inputFile) == false) { throw new FileNotFoundException("Input file is not present "); } // Read All line from file string[] allLine = File.ReadAllLines(@inputFile); int rowCount = allLine.Count(); int columnCount = allLine[0].Split(new char[] { columnDelimiter },
StringSplitOptions.RemoveEmptyEntries).Count(); int[,] matrix = new int[rowCount, columnCount]; for (int rowCounter = 0; rowCounter < rowCount; rowCounter++) { string[] line = allLine[rowCounter].Split(columnDelimiter); for (int columnConter = 0; columnConter < columnCount; columnConter++) { matrix[rowCounter, columnConter] = int.Parse(line[columnConter]); } } return matrix; }
 
input File 

11,12,13,14,15
21,22,23,24,25
31,32,33,34,35
41,42,43,44,45
51,52,53,54,55
16,17,18,19,20
26,27,28,29,30
36,37,38,39,40
46,47,48,49,50

 

Today we have to write a program for finding the balance index in a given array. This problem can be solved on O( n ) time.

Approach 1

  1. Loop Through the array and calculate the sum ,let’s assume sum is equal to arraySum.
  2. Now again again iterate over array elements
    1. Calculate the sum of element say it is leftsum
    2. calculate the difference between arraySum and current Element in arraySum
    3. if arraySum is equal to leftSum, then current array index is the balance index.
  3. Otherwise return –1, means balance index is not present in the array.

Code:

        public static int BalanceIndex(int[] input)
        {
            int arraySum = 0;
            int leftSum = 0;
            int balnaceIndex = -1;
            //Calculate the sum of all elements
            for (int i = 0; i < input.Length; i++)
            {
                arraySum = arraySum + input[i];
            }

            Console.WriteLine("Sum of Array Elements : " + arraySum);

            for (int i = 0; i < input.Length; i++)
            {
                leftSum = leftSum + input[i];
                arraySum = arraySum - input[i];
                if (arraySum == leftSum)
                {
                    balnaceIndex = i;
                    return balnaceIndex;
                }
            }

            if (leftSum != arraySum)
            {
                return -1;
            }
            return balnaceIndex;
        }

Test Case

private static void BalanceIndexTest()

{

    int[] arr = new int[] { -7, 1, 5, 2, -4, 3, 0,8 };

    Console.WriteLine("Balance index for " + string.Join(",", arr) + " is : " + ArrayProblems.BalanceIndex(arr));

    int[] arr1 = new int[] { 1, 3, 4, 6, 7, 2, 5, 9, 1, 11, 9, 6, 5, 8, 9, 1 };

    Console.WriteLine("Balance index for " + string.Join(",", arr1) + " is : " + ArrayProblems.BalanceIndex(arr1));

    int[] arr2 = new int[] { -7, 1, 5, 2, -4, 3, 0};

    Console.WriteLine("Balance index for " + string.Join(",", arr2) + " is : " + ArrayProblems.BalanceIndex(arr2));


    int[] arr3 = new int[] { -7 };

    Console.WriteLine("Balance index for " + string.Join(",", arr3) + " is : " + ArrayProblems.BalanceIndex(arr));


}

Output

Sum of Array Elements : 8

Balance index for -7,1,5,2,-4,3,0,8 is : –1

Sum of Array Elements : 87

Balance index for 1,3,4,6,7,2,5,9,1,11,9,6,5,8,9,1 is : –1

Sum of Array Elements : 0

Balance index for -7,1,5,2,-4,3,0 is : 5

Sum of Array Elements : -7

Balance index for -7 is : -1

 public static void RepeatedEvenTimes(int[] inputArray)
    {
      Dictionary<int, int> numbers = new Dictionary<int, int>();
      int length = inputArray.Length;
      int num = -1;
      for (int i = 0; i < length; i++)
      {
        if (numbers.Keys.Contains(inputArray[i]))
        {
          numbers[inputArray[i]] = numbers[inputArray[i]] + 1;
        }
        else
        {

          numbers.Add(inputArray[i], 1);
        }
      }

      Console.Write("input Array ");
      Console.WriteLine(string.Join(",", inputArray));

      foreach (var item in numbers)
      {
        if (item.Value % 2 == 0)
        {
          num = item.Key;
          Console.WriteLine("{0} Repeated {1} times ", item.Key, item.Value);
          break;
        }

      }

      if (num == -1)
      {
        Console.WriteLine("No number Repeated even number of times");
      }

      Console.WriteLine("-----------------------------------------------");
    }
 

input Array 3,3,3,5,5,5,2,2,2
No number Repeated even number of times
———————————————–
input Array 100,1,1,3,5,3,3
1 Repeated 2 times
———————————————–
input Array 2,2,2,2,2
No number Repeated even number of times
———————————————–

Find two numbers in an array whose sum =X

Solution : Here is the idea is to start from the first element of the array and keep a Hashtable to store the potential pairs. We will check  if sum – (a[i])  already exists in the Hashtable . If yes, we have a pair (a[i], value from Hashtable ) as the pair with the sum. If no, we store a[i] in the Hashtable .

Here is a little dry run of array a= {1,2,3,4,5,6,7,8} and sum = 6.

  1. 6 – 1 = 5  — found in Hashtable H ? No – store it in H.  H will contain (1)
  2. 6 –2 = 4 – found in Hashtable H ? No – store it in H.  H will contain (1, 2)
  3. 6 –3 = 4 – found in Hashtable H ? No – store it in H.  H will contain (1, 2, 3)
  4. 6 –4 = 2 – found in Hashtable H ? Yes – now we have a pair (a[i] , found in H) – (4,2)
  5. 6 –5 = 1 – found in Hashtable H ? Yes – now we have a pair (a[i] , found in H) – (5,1)
public static void TargetSum(int[] array, int target)
    {

      Dictionary<int, int> hashMap = new Dictionary<int, int>();

      int lookup = 0;

      for (int i = 0; i < array.Length; i++)
      {
        lookup = target - array[i];

        if (hashMap.ContainsKey(lookup) == true)
        {
          Console.WriteLine("Pair {0},{1}", lookup, array[i]);

        }
        else
        {
          hashMap.Add(array[i], array[i]);
        }
      }



    }