Tuesday, August 23, 2011

C# code to Arrange array values Columnwise

Question :
Format any given string array "columnwise" into 3 compact html columns 
(notice the example output is ordered by column, not by row) 
last row is only row that can be short (i.e. have one or two empty cells, see example below)
sample test case (your solution should pass any test case)  
string[] testArray = { "item 1", "item 2", "item 3", "item 4", "item 5", "item 6", "item 7", "item 8", "item 9", "item 10", "item 11" };
write your code here to create your html output from testArray[] as a string
Response.Write(@"<table>
                            <tr><td>item 1</td><td>item 5<td>item 9</td><td></td></tr>
                            <tr><td>item 2</td><td>item 6<td>item 10</td><td></td></tr>
                            <tr><td>item 3</td><td>item 7<td>item 11</td><td></td></tr>
                            <tr><td>item 4</td><td>item 8<td></td><td></td></tr>
                            </table>"); 
Answer
using System;
using System.Collections.Generic;
using System.Text;
/*
 * step 1 : Store array in arraylist
 * step 2 : Find out no of blank cells in table and assign blank value for those cells

 * step 3 : Shuffle the array for matrix
 * step 4 : Display in required formate
 * */
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
           
 string[] testArray = { "item 1", "item 2", "item 3", "item 4", "item 
5", "item 6", "item 7", "item 8", "item 9", "item 10", "item 11" };


            int noOfColumns = 3;
            StringBuilder sb = new StringBuilder();
            
            System.Collections.ArrayList tlist = new System.Collections.ArrayList()
;
            // Calculate no blankcells
            int blankArray = noOfColumns - (testArray.Length % noOfColumns);
           
            //populate the arrayvalues in ArrayList with blankcells
            for (int x = 0; x < testArray.Length + blankArray; x++)
            {
                if (testArray.Length > x)
                {
                    tlist.Add(testArray[x]);
                }
                else
                {
                    tlist.Add("");
                }
            }

            //Shuffle the array for matrix
            System.Collections.ArrayList list = new System.Collections.ArrayList()
;
            for (int i = 0; i < tlist.Count / 3; i++)
            {
                list.Add(tlist[i].ToString());
                list.Add(tlist[i + noOfColumns + 1].ToString());
                list.Add(tlist[i + (noOfColumns + 1) * 2].ToString());
            }
            // Add HTML tags and display the array
            sb.Append("<table>");
            for (int j = 0; j < 12; j = j + 3)
            {              
                sb.Append("<tr>");
                sb.Append("<td>" + list[j].ToString() + "</td><td>" + list[j + 1].ToString() + "</td><td>" + list[j + 2].ToString() + "</td>");
                sb.Append("</tr>");
               
            }
            sb.Append("</table>");
            Console.WriteLine(sb.ToString(
));
            Console.ReadLine();
        }

    }
}

C# code to find second largest Element in an array

Question : Write C# code to find second largset element in an Integer Array
Possible solutions
1. Store values in List and sort the list and find the 3rd element in the list
2.Use Hashtable
3.Use for loop
4.Use bubble sort or any other sorting algorithm and print 3rd element (Code snippet will be published later)

Use for loop
private static void getSecondLargest(int[] intArray)
        {
            int maxVal = 0;
            int secondMax = 0;

            for (int i = 0; i < intArray.Length; i++)
            {
                if (intArray[i] > maxVal)
                {
                    secondMax = maxVal;
                    maxVal = intArray[i];
                }
                else if (intArray[i] > secondMax)
                {
                    // Print Second Largest Value
                    secondMax = intArray[i];
                }
            }
            Console.WriteLine("Second Largest Value : "+secondMax);
        }


C# code to find the min value in an array

Question:  Write a method to find the min value in an array.

What an Interviewer is looking far?
Think about the test cases clearly
Example:
Your input array can be in any of the following format 
           int[] intArray = null;
            int[] intArray = {};
            int[] intArray = { 1, 2, 3, 4, 5 };
            int[] intArray = { 1, 3, 5, 7, 9 };
            int[] intArray = { -1, -2, -3, -4, -5 }; 
            int[] intArray = { -5, -2, 0, -4, 5 }; 
            int[] intArray = { -1, -5, -3, -4, -2 }; 

I can think about 20 different test case for this input array.

Possible Solutions:
1. Use Hashtable
2  Take a[0] as pivot and using a for-loop traverse the array and find the min element
3. Use sorting algorithm- Eg bubble sort.

a[0] as pivot element and find a min value of an array
 private static void getMinValue(int[] intArray) //throws Exception
        {
            if (intArray != null)
            {
                //throw new System.ArgumentNullException();// Exception("\n Invalid intArray as it is null");
                Console.ReadLine();
            }
            else
            {
                throw new Exception("exception for null");
                Console.WriteLine("I am in Null check else block");
            }
            if (intArray.Length == 0)
            {
                Console.WriteLine("There are no elements in the array");
                Console.ReadLine();
            }
            else
            {
                int min = intArray[0];
                for (int i = 0; i < intArray.Length; i++)
                {
                    if (intArray[i] < min)
                    {
                        min = intArray[i];
                    }
                }
                Console.WriteLine("Min value in the array : " + min);               
            }
        }
 

C# code sample for Singleton design pattern to get a DB Connection

Question : Sample code for Singleton design pattern to get a connection to the DB

Singleton can be use where there is a need to create only one instance of a given class

Here are some common examples:  File Handler, Print Spooler handler, Database connection, etc


Singleton class 
    public class ConnSingleton
    {
        private static ConnSingleton dbInstance;
        private readonly SqlConnection conn = new SqlConnection(@"Data Source=127.0.0.1;database=soa;User id=sa1;Password=sa1;");       
     
        private ConnSingleton()
        {
        }

        public static ConnSingleton getDbInstance()
        {
            if (dbInstance == null)
            {
                dbInstance = new ConnSingleton();
            }
            return dbInstance;
        }

        public SqlConnection GetDBConnection()
        {
            try
            {
                conn.Open();
                Console.WriteLine("Connected");
            }
            catch (SqlException e)
            {
                Console.WriteLine("Not connected : "+e.ToString());
                Console.ReadLine();
            }
            finally
            {
                Console.WriteLine("End..");
               // Console.WriteLine("Not connected : " + e.ToString());
                Console.ReadLine();
            }
            Console.ReadLine();
            return con;
        }

    }

Method to call from Main class:
 public static void Main(string[] args)
        {
            ConnSingleton cs = ConnSingleton.getDbInstance();
            cs.GetDBConnection();           
            Console.WriteLine("Connection Established");
        }

C# code sample for reversing a string

Question: Write a method to reverse a string

Test case:
string s = "This is Test";
Output string s="tseT si sihT";

Possible solutions:
1. Use Array.Reverse
2. Use for loop and print reverse
3. Use stack
4. Use recursion

1. Use Array.Reverse
// Using Reverse
        public static string ReverseString(string s)
        {
            char[] arr = s.ToCharArray();
            Array.Reverse(arr);
            return new string(arr);
        }

2. For loop
//Using For Loop to reverse string
        public static string RevStrForLoop(string s)
        {
            int len = s.Length;
            char[] arr = new char[len];
            for (int i = 0; i < s.Length; i++)
            {
                arr[i] = s[len-i-1];
            }
            return new string(arr);
        }

3.Use Stack
 public static string UsingStack(string s)
        {
            Stack<string> stack = new Stack<string>();
            string rs = string.Empty;

            for (int i=0; i<s.Length ; i++)
            {
                stack.Push(s.Substring(i,1));
               
            }
            for (int i = 0; i < s.Length; i++)
            {
                rs += stack.Pop();

            }
            return rs;
        }