Archive for the ‘ Array ’ Category

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

 

Write A Program To Print Matrix In Diagonal Order

Today we will write a program to print a given matrix in diagonal order.

 

        public void DiagonalOrder(int[,] input)
        {
            int rowcount = input.GetLength(0);
            int columnCount = input.GetLength(1);
            int rowIndex = -1;
            int columnIndex = 0;
            int startRowIndex = rowIndex;
            int startColumnIndex = columnIndex;
            while (true)
            {
                if (rowIndex < rowcount - 1)
                {
                    rowIndex++;
                }
                else if (rowIndex == rowcount - 1 && columnIndex < columnCount - 1)
                {
                    columnIndex++;
                }
                else if (rowIndex == rowcount - 1 && columnIndex == columnCount - 1)
                {
                    break;
                }
                startRowIndex = rowIndex;
                startColumnIndex = columnIndex;
                while (startRowIndex < rowcount && startRowIndex >= 0
                        && startColumnIndex < columnCount && startColumnIndex >= 0)
                {
                    Console.Write(input[startRowIndex, startColumnIndex] + " , ");
                    startRowIndex = startRowIndex - 1;
                    startColumnIndex = startColumnIndex + 1;

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

1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50

output

1 ,
11 , 2 ,
21 , 12 , 3 ,
31 , 22 , 13 , 4 ,
41 , 32 , 23 , 14 , 5 ,
42 , 33 , 24 , 15 , 6 ,
43 , 34 , 25 , 16 , 7 ,
44 , 35 , 26 , 17 , 8 ,
45 , 36 , 27 , 18 , 9 ,
46 , 37 , 28 , 19 , 10 ,
47 , 38 , 29 , 20 ,
48 , 39 , 30 ,
49 , 40 ,
50 ,

————————————————————————————————————————

input

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

Output

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

Given Matrix :

[1   14    25   35]
[2   16    28   38]
[5   20    28   40]
[16  22    38   41]  

search for 38.

public static void FindElementinSortedMatrix(int n)
        {

            int[,] myArray = {
                                 { 1, 14, 25, 35 },
                                 { 2, 16, 28, 38 },
                                 { 5, 20, 28, 40 },
                                 { 16, 22, 38, 41 }
                             };

            int i = 0;
            int j = myArray.GetLength(0) – 1;
            while (i < n && j >= 0)
            {
                if (myArray[i, j] == n)
                {
                    Console.WriteLine(string.Format("element Found at {0},{1}", i, j));
                    return;
                }
                else if (myArray[i, j] > n)
                {
                    j = j – 1;
                }
                else
                {
                    i = i + 1;
                }

            }
            Console.WriteLine("Element Not Found");
        }

Test Results

Element 38 Found at 1,3
Element 10 Not Found
Element -1 Not Found

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

Write a Program for Rotate a Sqaure Matrix by 90 Degree

Today we have to write a program for rotating a given matrix by 90 degree. This code only works with square matrix.

Code

        public static void MatrixRotation<T>(T[,] matrix)
        {
            Console.WriteLine("\n Input Matrix");
            Print2DMatrix(matrix);
            int row = matrix.GetLength(0);
            int column = matrix.GetLength(1);

            T temp;
            for (int i = 0; i < row; i++)
            {
                for (int j = i + 1; j < column; j++)
                {
                    temp = matrix[j, i];
                    matrix[j, i] = matrix[i, j];
                    matrix[i, j] = temp;
                }
            }


            for (int i = 0; i < row / 2; i++)
            {
                for (int j = 0; j < column; j++)
                {
                    temp = matrix[j, i];
                    matrix[j, i] = matrix[j, row - i - 1];
                    matrix[j, row - i - 1] = temp;
                }
            }
            Console.WriteLine("\n Rotation matrix");
            Print2DMatrix(matrix);

        }

        private static void Print2DMatrix<T>(T[,] matrix)
        {
            Console.WriteLine("--------------\n");
            int row = matrix.GetLength(0);
            int column = matrix.GetLength(1);

            for (int i = 0; i < row; i++)
            {
                for (int j = 0; j < column; j++)
                {
                    Console.Write(matrix[i, j] + " ");
                }
                Console.WriteLine(" ");
            }

        }

Result


Input Matrix

————–

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

Rotation matrix

————–

51 41 31 21 11

52 42 32 22 12

53 43 33 23 13

54 44 34 24 14

55 45 35 25 15

Input Matrix

————–

A B C D

E F G H

I J K L

M N O P

Rotation matrix

————–

M I E A

N J F B

O K G C

P L H D

Write a Program For Binary Search

Binary Search is used to find a given key in a sorted array. In each step, the algorithm compares the search key value with the key value of the middle element of the array. If the keys match, then a matching element has been found and its index, or position, is returned. Otherwise, if the search key is less than the middle element’s key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the search key is greater, on the sub-array to the right. If the remaining array to be searched is empty, then the key cannot be found in the array and a special "not found" indication is returned.

Code

        public static int BinarySearch(int[] input, int key)
        {

            int leftPointer = 0;
            int length = input.Length;
            int rightPointer = length - 1;
            int middlePointer = 0;

            while (rightPointer > leftPointer)
            {
                middlePointer = (rightPointer + leftPointer) / 2;

                if (input[middlePointer] < key)
                {
                    leftPointer = leftPointer + 1;
                }
                else if (input[middlePointer] > key)
                {
                    rightPointer = rightPointer - 1;
                }
                else
                {
                    return middlePointer;
                }
            }
            return -1;
        }

Write a Program to find all the Pythagorean triples.

Given a sorted array of integers and we have to find all Pythagorean triples.

Definition from Wikipedia : A Pythagorean triple consists of three positive integers a, b, and c, such that a2 + b2 = c2. Such a triple is commonly written (a, b, c), and a well-known example is (3, 4, 5).

Code :

        public static void PythagoreanTriple(int[] input)
        {

            int length = input.Length;
            if (length < 3)
            {
                Console.WriteLine("Length of Array can not be less then 3");
                return;
            }

            for (int i = 0; i < length; i++)
            {
                input[i] = input[i] * input[i];
            }

            int leftPointer = 0;
            int rightPointer = 0;
            int temp = 0;
            for (int i = length - 1; i > 1; i--)
            {
                leftPointer = 0;
                rightPointer = i - 1;
                temp = input[i]; ;
                while (leftPointer < rightPointer)
                {
                    if (input[leftPointer] + input[rightPointer] == temp)
                    {
                        Console.WriteLine(Math.Sqrt(input[leftPointer]) + ";" 
+ Math.Sqrt(input[rightPointer])
+ ";" + Math.Sqrt(input[i])); break; } else if (input[leftPointer] <= input[rightPointer]) { leftPointer++; } else { rightPointer--; } } } }
Test Case: 
Input Output
{ 1, 3, 4,5, 6, 7, 8, 10, 11 } 6;8;10

3;4;5
{ 1, 3, 4,5, 6, 7, 8, 10, 11,12,13 }

5;12;13

6;8;10

3;4;5

{ 5, 6, 7, 8, 10, 11,12,13,14,15,17 }

8;15;17

5;12;13

6;8;10



Write a Program for Finding Duplicate Elements in Array

Given an array of n elements and elements are  from 1 to n-1. that is

clip_image002[6]

Code

        public static void PrintDuplicate(int[] input)
        {
            int length = input.Length;
            Console.WriteLine(string.Join(";", input));
            for (int i = 0; i < length; i++)
            {
                if (input[Math.Abs(input[i])] >= 0)
                {
                    input[Math.Abs(input[i])] = -input[Math.Abs(input[i])];

                }
                else
                {
                    Console.WriteLine("duplicate number {0} and it's index is {1} ",
Math.Abs(input[i]), i + " ; "); } } }

Today We will write a program for converting matrix’s row and columns to zero if any one element is zero.

Example

Input Output

2 2 2 2

2 0 2 3

2 2 2 2

2 0 2 2

0 0 0 0

2 0 2 2

Code

        public static void RowColumnZero(int[,] matrix)
        {
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("Before");
            Print2DMatrix(matrix);
            int rowConter;
            int columnCounter;

            rowConter = columnCounter = 0;
            int[] rowArray = new int[matrix.GetLength(0)];
            int[] columnArray = new int[matrix.GetLength(1)];

            for (rowConter = 0; rowConter < rowArray.Length; rowConter++)
            {

                for (columnCounter = 0; columnCounter < columnArray.Length; 
columnCounter++) { if (matrix[rowConter, columnCounter] == 0) { rowArray[rowConter] = 1; columnArray[columnCounter] = 1; } } } for (rowConter = 0; rowConter < rowArray.Length; rowConter++) { for (columnCounter = 0; columnCounter < columnArray.Length;
columnCounter++) { if (rowArray[rowConter] == 1 || columnArray[columnCounter] == 1) { matrix[rowConter, columnCounter] = 0; } } } //Print output Console.WriteLine("After"); Print2DMatrix(matrix); Console.WriteLine("------------------------------------------------------");
        }
Program For Creating the Matrix 
        public static int[,] CreateTestMatrix(int row, int column)
        {
            int[,] matrix = new int[row, column];
            int i, j;
            Random rnd = new Random();
            for (i = 0; i < row; i++)
            {
                //create a test matrix
                for (j = 0; j < column; j++)
                {
                    matrix[i, j] = rnd.Next(0, row * column);
                }
            }
            return matrix;
        }

Program for Printing the Matrix

        private static void Print2DMatrix(int[,] matrix)
        {
            for (int rowConter = 0; rowConter < matrix.GetLength(0); rowConter++)
            {
                {
                    for (int columnCounter = 0; columnCounter < matrix.GetLength(1); 
columnCounter++) { Console.Write(matrix[rowConter, columnCounter] + " "); } Console.WriteLine(Environment.NewLine); } } }
Test
Input Output

6 0 9 11

7 3 10 5

10 5 11 3

0 0 0 0

7 0 10 5

10 0 11 3

7 8 5 3

8 8 11 19

15 19 0 19

7 7 9 11

14 8 16 6

7 8 0 3

8 8 0 19

0 0 0 0

7 7 0 11

14 8 0 6

6 0 3

5 5 3

6 8 6

0 0 0

5 0 3

6 0 6

5 11 6 8

9 5 7 5

13 7 1 7

0 12 9 12

0 11 6 8

0 5 7 5

0 7 1 7

0 0 0 0

2 6 3

4 5 3

4 3 7

2 6 3

4 5 3

4 3 7

1 1

3 1

1 1

3 1

Today We will write a program for converting matrix’s row and columns to zero if any one element is zero.

Example

Input Output

2 2 2 2

2 0 2 3

2 2 2 2

2 0 2 2

0 0 0 0

2 0 2 2

Code

        public static void RowColumnZero(int[,] matrix)
        {
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("Before");
            Print2DMatrix(matrix);
            int rowConter;
            int columnCounter;

            rowConter = columnCounter = 0;
            int[] rowArray = new int[matrix.GetLength(0)];
            int[] columnArray = new int[matrix.GetLength(1)];

            for (rowConter = 0; rowConter < rowArray.Length; rowConter++)
            {

                for (columnCounter = 0; columnCounter < columnArray.Length; 
columnCounter++) { if (matrix[rowConter, columnCounter] == 0) { rowArray[rowConter] = 1; columnArray[columnCounter] = 1; } } } for (rowConter = 0; rowConter < rowArray.Length; rowConter++) { for (columnCounter = 0; columnCounter < columnArray.Length;
columnCounter++) { if (rowArray[rowConter] == 1 || columnArray[columnCounter] == 1) { matrix[rowConter, columnCounter] = 0; } } } //Print output Console.WriteLine("After"); Print2DMatrix(matrix); Console.WriteLine("------------------------------------------------------");
        }
Program For Creating the Matrix 
        public static int[,] CreateTestMatrix(int row, int column)
        {
            int[,] matrix = new int[row, column];
            int i, j;
            Random rnd = new Random();
            for (i = 0; i < row; i++)
            {
                //create a test matrix
                for (j = 0; j < column; j++)
                {
                    matrix[i, j] = rnd.Next(0, row * column);
                }
            }
            return matrix;
        }

Program for Printing the Matrix

        private static void Print2DMatrix(int[,] matrix)
        {
            for (int rowConter = 0; rowConter < matrix.GetLength(0); rowConter++)
            {
                {
                    for (int columnCounter = 0; columnCounter < matrix.GetLength(1); 
columnCounter++) { Console.Write(matrix[rowConter, columnCounter] + " "); } Console.WriteLine(Environment.NewLine); } } }
Test
Input Output

6 0 9 11

7 3 10 5

10 5 11 3

0 0 0 0

7 0 10 5

10 0 11 3

7 8 5 3

8 8 11 19

15 19 0 19

7 7 9 11

14 8 16 6

7 8 0 3

8 8 0 19

0 0 0 0

7 7 0 11

14 8 0 6

6 0 3

5 5 3

6 8 6

0 0 0

5 0 3

6 0 6

5 11 6 8

9 5 7 5

13 7 1 7

0 12 9 12

0 11 6 8

0 5 7 5

0 7 1 7

0 0 0 0

2 6 3

4 5 3

4 3 7

2 6 3

4 5 3

4 3 7

1 1

3 1

1 1

3 1