Archive for August, 2013

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 ,

Find Maximum Occurrence of a Character in a Given String

        public static char MaximumOccurringCharacter(this string input)
        {
           
SortedDictionary<char, int> charDict = new SortedDictionary<char, int
>();
           
int
length = input.Length;

            for (int i = 0; i < length; i++)
            {
               
if
(charDict.ContainsKey(input[i]))
                {
                    charDict[input[i]]++;
                }
               
else
               
{
                    charDict.Add(input[i], 1);
                }
            }

            var max = charDict.Values.Max();
           
var
relevantKeys = charDict.Where(pair => max.Equals(pair.Value))
                .Select(pair => pair.Key).First();
           
return
relevantKeys;

        }

Test Case

Console.WriteLine("Max occur char in string test is : " + "test".MaximumOccurringCharacter());

Console.WriteLine("Max occur char in string maximum is : " + "maximum".MaximumOccurringCharacter());

Console.WriteLine("Max occur char in string MaximumOccurringCharacter is : " + "MaximumOccurringCharacter".MaximumOccurringCharacter());

Output

Max occur char in string test is : t
Max occur char in string maximum is : m
Max occur char in string MaximumOccurringCharacter is : r

Iterative Method for Finding Height Of Tree

For finding the height of the tree we can use level order traversal of three. We  need to traverse the tree level by level and increment the height count.

        public int IterativeHeightOfTree(TreeNode root)
        {
            int height = 0;
            if (root == null)
            {
                return height;
            }
            int nodes = 0;
            Queue<TreeNode> queue = new Queue<TreeNode>();
            queue.Enqueue(root);
 
            while (true)
            {
                nodes = queue.Count();
                if (nodes == 0)
                {
                    return height;
                }
                height = height + 1;
                while (nodes > 0)
                {
                    var temp = queue.Dequeue();
                    if (temp.Left != null)
                    {
                        queue.Enqueue(temp.Left);
                    }
                    if (temp.Right != null)
                    {
                        queue.Enqueue(temp.Right);
                    }
                    nodes = nodes - 1;
                }
 
            }
 
            //return height;
        }

Test Case

Tree Node count is :  20
5,3,9,15,13,9,7,18,2,13,1,5,7,19,13,13,6,12,14,14,
Height of Tree is 5

Tree Node count is :  1
1,
Height of Tree is 1

Tree Node count is :  0
Height of Tree is 0

Write a program to calculate power(x,n)

Below solution divides the problem into sub problems of size y/2 and call the sub problems recursively

public static UInt64 Power(UInt64 x, UInt64 n)
{
    if (n == 0)
        return 1;
    else if (n % 2 == 0)
        return Power(x, n / 2) * Power(x, n / 2);
    else
        return x * Power(x, n / 2) * Power(x, n / 2);

}

Test Case

UInt64 x = 0;
UInt64 n = 0;
x = 2; n = 2;
Console.WriteLine(string.Format("{0}^{1} ={2}", x, n, Power(x, n)));
x = 2; n = 3;
Console.WriteLine(string.Format("{0}^{1} ={2}", x, n, Power(x, n)));
x = 10; n = 2;
Console.WriteLine(string.Format("{0}^{1} ={2}", x, n, Power(x, n)));
x = 12; n = 18;
Console.WriteLine(string.Format("{0}^{1} ={2}", x, n, Power(x, n)));
Console.Read();

Output

2^2 =4
2^3 =8
10^2 =100
12^18 =8176589207175692288

Write code to check a String is palindrome or not

A palindrome is a word, phrase, number, or other sequence of symbols or elements, whose meaning may be interpreted the same way in either forward or reverse direction.

public static bool IsPalindrome(this string input)
     {
         bool result = true;
         input = input.Trim();
         try
         {

             if (string.IsNullOrEmpty(input))
             {
                 return result = false;
             }

             var inputArray = input.ToCharArray();

             if (inputArray.Length == 1)
             {
                 return result = true;
             }

             int length = inputArray.Length – 1;

             for (int i = 0; i <= length / 2; i++)
             {
                 if (inputArray[i] != inputArray[length – i])
                 {
                     return result == false;
                 }
             }
         }
         catch (Exception)
         {

             result = false;
         }
         return result;

     }
Test Case

string s = "";
Console.WriteLine(string.Format("String {0} IsPalindrome {1}", s, s.IsPalindrome()));
s = "AJAY";
Console.WriteLine(string.Format("String {0} IsPalindrome {1}", s, s.IsPalindrome()));
s = "ABBA";
Console.WriteLine(string.Format("String {0} IsPalindrome {1}", s, s.IsPalindrome()));
s = "ABBa";
Console.WriteLine(string.Format("String {0} IsPalindrome {1}", s, s.IsPalindrome()));
s = "palindrome";
Console.WriteLine(string.Format("String {0} IsPalindrome {1}", s, s.IsPalindrome()));

Output:

String  IsPalindrome False
String AJAY IsPalindrome False
String ABBA IsPalindrome True
String ABBa IsPalindrome False
String palindrome IsPalindrome False

Reverse a Given Number C#

 

        public static long ReverseNumber(this long number)
        {
            long reversedNumber = 0;
            bool isNegative = false;
 
            if (number < 0)
            {
                isNegative = true;
            }
            if (number < 10 && number >= 0)
            {
                reversedNumber = number;
                return reversedNumber;
            }
 
            number = Math.Abs(number);
 
            while (number > 0)
            {
                reversedNumber = _base * reversedNumber + number % _base;
                number = number / _base;
            }
 
            if (isNegative)
            {
                reversedNumber = reversedNumber * -1;
            }
            return reversedNumber;
        }

 

Test Case

Number 1234567890 is reversed to 987654321

Number -123456 is reversed to -654321

Number 9 is reversed to 9

Number 545 is reversed to 545

Number 123454321 is reversed to 123454321

Number -123454321 is reversed to -123454321