Monday, July 1, 2013

Write a method to capitalize all vowels in a string (C#)

   
    static void Main(string[] args)
        {
           
            string input = "Clematis require a site that will receive at least one half day of direct sunlight. This helps in bud and bloom production, and in lowering susceptibility to crown rot.   Young clematis are extremely susceptible to crown rot, which is a disease. Crown Rot can usually be prevented by treating the plant with a garden or flower fungicide throughout the growing season.";
            Console.WriteLine (capitalizeVowels(input));
            Console.ReadKey();
            }

First Approach : Using a StringBuilder to hold the intermidiate string.

 public static string capitalizeVowels(string input)
        {
                       if (string.IsNullOrEmpty(input))
                return input;
            else
            {
                HashSet vowels = new HashSet { 'a', 'e', 'i', 'o', 'u' };
                StringBuilder result = new StringBuilder();
                foreach (var i in input)
                {
                    result.Append(vowels.Contains(i) ? char.ToUpper(i) : i);

                }
                return result.ToString();
            }
        }

Second Approach : Using Linq

  public static string capitalizeVowels(string input)
        {
            if (string.IsNullOrEmpty(input))
                return input;
            else
            {
                HashSet vowels = new HashSet { 'a', 'e', 'i', 'o', 'u' };
                return new string(input.Select(x => vowels.Contains(x) ? char.ToUpper(x) : x).ToArray());
            }
        }
 

Monday, June 24, 2013

• What does NULL mean in SQL?

In SQL, the value NULL means UNKNOWN; it does not mean '' (empty string). Assuming ANSI_NULLS are on in your SQL Server database, which they are by default, any comparison to the value NULL will yield the value NULL. You cannot compare any value with an UNKNOWN value and logically expect to get an answer. You must use the IS NULL operator instead.

Thursday, June 20, 2013

Print all possible combinations of r elements in a given array of size n (C#)

For this question, I have taken an array of size 5 and printed all combinations of length 3. I used Linq query for doing this.

Solution


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
namespace Excercises
{
    class Program
    {
        static void Main(string[] args)
        {
            //To generate all the length-3 combinations of integers from the set {1, 2, 3, 4, 5}:
            int[] Arr = { 1, 2, 3, 4, 5 };
                var combo = from a in Arr
                            from b in Arr
                            from c in Arr
                            select string.Concat(a,b,c);
            foreach (var v in combo)
            {
            Console.WriteLine(v);
            }
            Console.ReadKey();
        }

    }
}

Tuesday, June 18, 2013

Find the least number in a given array of integers (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Collections;
namespace examples
{
    class Program
    {
        static void Main(string[] args)
        {

//The option I chose is to sort the array (Bubble sort) and return the integer in the first index.

            int[] Arr = { 1, 10, -5, 10, 12,6,2,-9,0,4,2 };
            for (int i= 0; i < Arr.Length; i++)
            {
                for (int j = i; j < Arr.Length; j++)
                {
                    if (i == j)
                    {
                       
                    }
                    else
                    {
                        if (Arr[i] <= Arr[j])
                        {
                            //break;
                        }
                        else
                        {
                            int temp = Arr[j];
                            Arr[j] = Arr[i];
                            Arr[i] = temp;
                        }
                    }
                }
            }
                Console.WriteLine("The lowest value in the array is {0}", Arr[0]);
                Console.ReadKey();
           
        }
    }
}
 

Sunday, June 16, 2013

What will be the approach to find the word which occurs maximum number of times in a very large file. (C#)

To find a word that occurs the maximum number of times in a very large file, the entire file will have to be scanned for the occurrence of the word. Since the file is very large, it will be efficient to process the file and find the occurrence of the word asynchronously. After the file is read in a fileStream, we can have different threads to process the file in chunks simultaneously. The threads will wait till processing for the file in each thread is over. Then the word with maximum count in the file will be determined.

Friday, June 14, 2013

How do you sort an array of 100 million values, given that the values are positive and unique. Disregard the space complexity of the solution i.e. assume that you have sufficient memory.

At first glance this question sounds baffling, even though it relaxes one of the criteria of space complexity. For sorting a data store that large, the time complexity is also critical.

Here is an approach which I thought was quite ingenuous. It also takes advantage of the available space. Here goes...

Solution  


Create an array of bits whose length is the length of the maximum value of an unsigned integer. In this array, each element has a default value of 0.

So the array looks like this:

          0 , 1 ,2 , 3, 4, 5,....                                                .....N
B[] = [0][0][0][0][0][0][0][0][0][0][0][0]......[0][0][0][0][0][0]

where N is the maximum value of an unsigned integer.

Now parse the source array of numbers and for each number encountered in the source, index that into the bit array above to set that bit (i.e. change it to 1).

e.g. If S[0] = 2345 then B[2345] = 1, i.e. that corresponding index has its bit flag set to indicate that the value is in the source array.

As each of the values is considered as a lookup in the bit array, the numbers are implicitly sorted since they are indices on a contiguous memory location. The values which do not occur in the array would not have their bit flag set.

Another "side-effect" of this process is that searching for any number can be done in constant time, since it gets converted to an array lookup which is O(1). So if you want to find if a number exists in this array, all you have to do is to index the bit array and check the bit flag at that index location - if it is set then the number exists, otherwise it does not!

e.g. if you want to find if 34987 exists in the source array, check if B[34987] = 1 or 0. If it is 1 then it exists, else it does not.



Wednesday, June 12, 2013

You have a set of (x,y) corordinates - like a list of .NET Point object - that form a line when plotted on a graph. If you are given a new (x,y) co-ordinate, find if it is a point in that line. (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Practice
{
    class Program
    {
        static void Main(string[] args)
        {
           
            List list = new List();
            Points P1 = new Points();
            P1.x = 2;
            P1.y = 4;
            Points P2 = new Points();
            P2.x = 6;
            P2.y = 1;

            Points P3 = new Points();
            P3.x = 7;
            P3.y = 4;
            list.Add(P1);
            list.Add(P2);
            list.Add(P3);
            Points P = new Points();
            P.x = 0;
            P.y = 7;
            int slope = findSlope(list);
            int newSlope = (P.y - P2.y) / (P.x - P2.x);
            Console.WriteLine((slope == newSlope).ToString());
            Console.ReadKey();
        }

//The structure of the Points object
  public  struct Points
       {
         public int x;
          public int y;
       }
public static int findSlope(List pointsList)
        {
    //    Get the 'X' and 'Y' values of any two points

        
           int x1 = pointsList.ElementAt(0).x;
            int x2 = pointsList.ElementAt(1).x;
            int y1 = pointsList.ElementAt(0).y;
            int y2 = pointsList.ElementAt(1).y;


//The slope is calculated by dividing the difference between Y co-ordinates by the difference of 'X' co-ordinates of two points

            int slope = (y2 -y1)/(x2 -x1);
            return slope;
        }
    }
}

Given a string, return start position of largest repeated characters (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
namespace Excercises
{
    class Program
    {
        static void Main(string[] args)
        {
   String string1 = "aaaaabbbbbbbbbbbbbbefxsscc";
  //String string2 = "aaaaaa";
        int pos = findStartPos(string1);
        Console.WriteLine(pos.ToString());
        Console.ReadKey();
        }
   

        public static int findStartPos(string str)
        {
            //this is the start position of the concurrent longest string
            int start = 0;
            //if another longer string is encountered, this becomes the start of the longer concurrent string
            int newStart = 0;
            //count of chars in the string
            int count = 1;
            //maximum length of the substring of con current chras
            int maxCount = 1;
            if (str.Length > 0)
            {
                char[] strArr = str.ToCharArray();
                for (int i = 1; i < strArr.Length; i++)
                {
                    if (strArr[i] == strArr[i - 1])
                    {
                        count++;
                        if (count > maxCount)
                        {
                            start = newStart;
                            maxCount = count;
                        }
                       
                    }
                    else
                    {
                        newStart = i;
                        count = 1;
                    }
                }
            }
            return start;
        }

 }
}

Given a two dimensional matrix of booleans, write a function that returns the number of "true regions". (C#)

Given a two dimensional matrix of booleans, there is a function that returns the number of "true regions". A region is a group of True values aligned vertically or horizontally.
T T    <= 3 region
T F
T F    <= 2 regions
F T

Question

Write the code to solve this problem. What are the time and space complexities?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
namespace Excercises
{
    class Program
    {
        static void Main(string[] args)
        {
            bool[,] region1 = new bool[2,2]{ { true, false }, { true, true }};
           
            int numOfRegions = returnRegion(region1);
            Console.WriteLine(numOfRegions.ToString());
            Console.ReadKey();
        }
        public static int returnRegion(bool[,] region1)
        {
         
            int count =0;
            int rowLen = region1.GetLength(0);
            int columnLen = region1.GetLength(1);
            for (int row = 0; row < rowLen ; row++)
            {
                for (int column = 0; column < columnLen; column++)
                {
                    if (region1[row, column] == true)
                    {
                        count++;
                    }
                }
            }
            return count;
        }
              
        }
    }

Complexity is O(2N)

Given an array of integers,write a function that retrieves unique instances of any duplicates, returning them in a new array. (C#)

Question


Given an array of integers, write a function that retrieves unique instances of any duplicates, returning them in a new array -
[2,1,2,4,3,1,5,1]  should return= [2,1] 
[1,1,1,1,1,1,1,1,1] should return =[1]

Solution


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
namespace Excercises
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] Arr = new int[] { 2, 1, 2, 4, 3, 1, 5, 1 };
            int[] DupArr = findDups(Arr);
            foreach (var i in DupArr)
            {
                if (i != 0)
                {
                    Console.WriteLine(i + ",");
                }
            }
            Console.ReadKey();
        }
        public static int[] findDups(int[] arr)
        {
            Dictionary Dic = new Dictionary();
//Giving an arbitrary array with arbitrary length 10         

  int[] newArr = new int[10];
            foreach (int i in arr)
            {
                if (Dic.ContainsKey(i))
                {
                    Dic[i]++;
                }
                else
                {
                    Dic.Add(i, 1);
                }
            }
            foreach (var v in Dic)
            {
                if (v.Value > 1)
                {
                    newArr[v.Key] = v.Key;
                }
            }
            return newArr;
        }
      
        }
    }


 

Monday, June 10, 2013

Write a query to delete duplicate rows in a table (SQL)

Delete duplicate records from the emp table


The Row_Number() built in function returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.
So when for a partition by empID, ROW_NUMBER() function will return the numbered rows grouped by empID.
The result set of the flowing query shows the data returned by row_number() function :

SELECT empid, ROW_NUMBER() over (PARTITION BY empid ORDER BY empid) as rowNum
 FROM [MySampleDB].[dbo].[emp]

The result set looks like :


To delete only duplicate records from the table, we have to delete only those rows for which the rowNumber is more than 1.

The following query will remove duplicates from the table :

WITH
temp_table AS
(SELECT empid, ROW_NUMBER() over (PARTITION BY empid ORDER BY empid) as rowNum
 FROM [MySampleDB].[dbo].[emp]
 )
DELETE FROM temp_table
WHERE rowNum > 1

Find the longest palindrome in a given string (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "paliniladrome";
            string longestPalindrome = GetMaxPalindromeString(str);
            Console.WriteLine(longestPalindrome);
            Console.ReadKey();
          
        }
        public static string GetMaxPalindromeString(string testingString)
        {
            int stringLength = testingString.Length;
            int maxPalindromeStringLength = 0;
            int maxPalindromeStringStartIndex = 0;
            for (int i = 0; i < stringLength; i++)
            {
                int currentCharIndex = i;
                for (int lastCharIndex = stringLength - 1; lastCharIndex > currentCharIndex; lastCharIndex--)
                {
                    if (lastCharIndex - currentCharIndex + 1 < maxPalindromeStringLength)
                    {
                        break;
                    }
                    bool isPalindrome = true;
                    if (testingString[currentCharIndex] != testingString[lastCharIndex])
                    {
                        continue;
                    }
                    else
                    {
                        int matchedCharIndexFromEnd = lastCharIndex - 1;
                        for (int nextCharIndex = currentCharIndex + 1; nextCharIndex < matchedCharIndexFromEnd; nextCharIndex++)
                        {
                            if (testingString[nextCharIndex] != testingString[matchedCharIndexFromEnd])
                            {
                                isPalindrome = false;
                                break;
                            }
                            matchedCharIndexFromEnd--;
                        }
                    }
                    if (isPalindrome)
                    {
                        if (lastCharIndex + 1 - currentCharIndex > maxPalindromeStringLength)
                        {
                            maxPalindromeStringStartIndex = currentCharIndex;
                            maxPalindromeStringLength = lastCharIndex + 1 - currentCharIndex;
                        }
                        break;
                    }
                }
            }
            if (maxPalindromeStringLength > 0)
            {
                return testingString.Substring(maxPalindromeStringStartIndex, maxPalindromeStringLength);
            }
            return null;
        }
    }
}
  

Sunday, June 9, 2013

Find the factorial on a whole number (C#)

Calculating factorials opens the doors to a discussion about stack overflow (if done recursively) and integer overflow (if the param is too large) as well as discussions around how to handle and catch errors.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Factorial
{
    class Program
    {
        static void Main(string[] args)
        {      
              //Find the factorial of a given integer
            int n = 6;
            int factor = RecursiveFactorial(n);
            Console.WriteLine("Recursive factorial result : {0}",factor);
            int factorInterative = IterativeFactorial(n);
            Console.WriteLine("Iterative factorial result : {0}", factorInterative);
            Console.ReadKey();
    
        }
        public static int RecursiveFactorial(int n)
        {
            if (n <= 1)
                return 1;
            else if (n>=1)
            {
                try
                {
                    return n * RecursiveFactorial(--n);
                   
                }
                catch (Exception ex)
                {

                }
            }
           return 1;
        }
        public static int IterativeFactorial(int n)
        {
            if (n <= 0)
                return 0;
            int factor = 1;
            try
            {
                for (int i = 1; i <= n; i++)
                {
                    factor *= i;
                }
                return factor;
            }
            catch (Exception ex)
            {

            }
            return 1;
        }
    }
}

Friday, June 7, 2013

How to find records for the last 2 days from a database? (SQL)

//Find records for the last 2 days

SELECT * FROM tableName
WHERE LogDateTime >= DATEADD (DD, -2, GETDATE());

//Find records for the last 2 hours

SELECT * FROM tableName
WHERE LogDateTime >= DATEADD (HOUR, -2, GETDATE());

Thursday, June 6, 2013

Finding the 3rd highest salary of an employee. (SQL)

Question


From the employee table, find the employee who earns the 3rd highest salary.



Solution

SELECT TOP 1 * FROM dbo.emp E
WHERE E.Salary IN
(SELECT TOP 3 Salary FROM dbo.emp
ORDER BY Salary desc)
ORDER BY E.Salary asc


 

Wednesday, June 5, 2013

Cricket Match score keeping (C#)

Question


Given a list of 30 whole numbers, each number representing the runs scored by a player in cricket per ball, write a C# program to find the following:
  1. Run rate, which is the runs per over. 6 balls make an over.
  2. Assuming that every 2 overs was played be a new batsman, calculate the batting average for each batsman. Batting average is the number of runs scored per ball played by that batsman.

Solution



//Calculate the run rate
public static double ranRateCalculator(List runs)
{
int totalRuns = 0;
foreach (int i in runs)
{
totalRuns += i;
}

//Total overs are the number of times the runs are entered in the list divided by 6 since 6 balls make an over.
int totalOvers = runs.Count / 6;

//runRate is the total runs per over
double ranRate = (double)totalRuns / totalOvers;
return runRate;
}

//Calculate the batting average for each batsman
 public static List ranRateCalculator(List runs)
 {
//Total overs are the number of times the runs are entered in the list divided by 6 since 6 balls make an over.
int totalOvers = (runs.Count)/6;
//total number of batsman are the total number of overs divided by 2 since the batsman change every 2 overs. If the total over is not exactly divisible by 2, then the number of batsman increase by one to play the remaining overs.
 int batsmanNum = totalOvers / 2;
 if (totalOvers%2 != 0)
 batsmanNum = batsmanNum + 1;
//Store the average scores per batsman in a list
 List avgPerBatsman = new List();
 for (int I-0; i < batsmanNum; i++)
 {
// find the runs scored by the first batsman, the second etc.
 var totalRunsPerBatsman = runs.Skip(i*12).Take(12);
 int total =0;
 foreach (var n in totalRunsPerBatsman)
 {
total += n;
}
double avg = (double) total / 12;

avgPerBatsman.Add(avg);
}

}
return avgPerBatsman;

//Calling the functions
public void Main()
{
List runs = new List{3,2,0,4,6,2,1,0,6,5,4,3,2,1,4,5,3,2,1,0,0,5,6,3,4,3,2,0,4,6};
// Finding the total run rate
 double runRate = runRateCalculator(runs);
 Console.Write("the run rate is {0}", runRate);
 Console.ReadKey();
//Finding the run rate for each batsman
 List avg = batsmanAvg(runs);
 foreach (var v in avg)
 {
 Console.WriteLine("The batsman average score are : {0}", v);
 }
 Console.ReadKey();
 }
 

Tuesday, June 4, 2013

Finding Fibonicci sequence (C#)

Question


Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... Find the sum of all the even-valued terms in the sequence which do not exceed four million.

Solution


//The method that returns a list of Fibonacci number sequence up to an input number.

public static List Fibonacci(int n)
{
//The first 2 numbers are given and stored in long variables. Add these numbers to the list
long a =1;
long b = 2;

List <int> sequence = new List<int>();

sequence.Add(a);
sequence.Add(b);

int i= sequence.Count;

if (n > 0)
{
while (i< n)
{
long temp = a;
a=b;
b = temp + a;
sequence.Add(b);
i ++ ;
}
}
return sequence;
}

//Calling the method to generate a list of Fibonacci number up to 4000000
Static void Main()
{
int n=4000000;

List list = Fibonacci(n);

//Iterate through the elements of the list and if it is a positive number, keep the sum of the numbers in an long variable and return the sum

int sum =0;

foreach (var v in list)
{
if (v%2 == 0)
{
sum += v;
}
}
Console.WriteLine(sum);
Console.ReadKey();
}

 

Sunday, June 2, 2013

Could not establish trust relationship for the SSL/TLS secure channel with authority PC1. (C#)

Overriding errors for trust relationship failures by trusting all certificates

While developing an application, I needed to browse to a url to read a file. Accessing the server url threw a error. So I added a method to trust all certificates from the url before I called the url.. That resolved the issue I was facing.


Code Snippet

Added this code before calling the server url :

// Trust all certificates

System.Net.ServicePointManager.ServerCertificateValidationCallback =
((sender, certificate, chain, sslPolicyErrors) => true);
   

Thursday, May 30, 2013

What is a Self join in SQL? Explain with examples. (SQL)

Self join is just like any other join, except that two instances of the same table will be joined in the query.
Here is an example: Employees table which contains rows for normal employees as well as managers. So, to find out the managers of all the employees, you need a self join.
CREATE TABLE emp
(
empid int,
mgrid int,
empname char(10)
)

INSERT emp SELECT 1,2,'Vyas'
INSERT emp SELECT 2,3,'Mohan'
INSERT emp SELECT 3,NULL,'Shobha'
INSERT emp SELECT 4,2,'Sridhar'
INSERT emp SELECT 5,2,'Sourabh'

//Query which will return employees who have managers

SELECT t1.empname [Employee], t2.empname [Manager]
FROM emp t1, emp t2
WHERE t1.mgrid = t2.empid

//Query using a LEFT OUTER JOIN that returns the employees without managers (super bosses)

SELECT t1.empname [Employee], COALESCE (t2.empname, 'No Manager') [Manager]
FROM emp t1
LEFT OUTER JOIN emp t2
ON t1.mgrid =t2.empid


 

Monday, May 27, 2013

String Reversal (C#)

class Program()
{
static void Main()
{
string str = "this is a string";
char[] charArr = str.ToCharArray();
StringBuilder build = new StringBuilder();

for (int i = charArr.lenght-1; i >=0; i--)
{
build.Append(charArr[i]);
}
Console.WriteLine(build.ToString());
Console.ReadKey();
}
}

What is the difference between a ref and out keyword? (C#)

The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed. For example:
class OutExample
{
    static void Method(out int i)
    {
        i = 44;
    }
    static void Main()
    {
        int value; Method(out value);
        // value is now 44     }
}

class RefExample
    {
        static void Method(ref int i)
        {
           // The following statement would cause a compiler error if 'i' were boxed as an object.            

 i = i + 44;
        }
        static void Main()
        {
            int val = 1;
            Method(ref val);
            Console.WriteLine(val);
            // Output: 45         }
    }
Although variables passed as an out arguments need not be initialized prior to being passed, the calling method is required to assign a value before the method returns.

The ref and out keywords are treated differently at run-time, but they are treated the same at compile time. Therefore methods cannot be overloaded if one method takes a ref argument and the other takes an out argument. These two methods, for example, are identical in terms of compilation, so this code will not compile.

class CS0663_Example
{
    // compiler error CS0663: "cannot define overloaded methods that differ only on ref and out"     public void SampleMethod(out int i) {  }
    public void SampleMethod(ref int i) {  }
}

Overloading can be done, however, if one method takes a ref or out argument and the other uses neither, like this:

class RefOutOverloadExample
{
    public void SampleMethod(int i) {  }
    public void SampleMethod(out int i) {  }
}

Find the sum of all natural numbers which are multiples of 3 and 5 below 1000. (C#)

Question


If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

Solution


static void Main()
{
//List all numbers below 100 which are multiples of 3 or 5
List Multiples = new List();
for (int i=0; i<1000 i="" int="">
{
if (i%3 ==0) || (i%5==0)
{
Multiples.Add(i);
}
}
Console.Write (Multiple.Sum());
Console.ReadKey();
 
 

Write a method to print out multiplication tables (C#)

Question


Write a method where when you input a number, it prints out a multiplication table of column header times row headers up to the input number. For example, if input = 2, it would write a table with 1 times 1, 1 times 2, 2 times 1 and 2 times 2.

Solution


class Program
{
static void Main ()
{
int input = 10;
if (input <=0)
{
Console.Write("No table");
}
else
{
int[ , ] table = new int[input,input];
 for(int i =0; I < input; i++)
 {
 for (int j =0; j < input; j++)
 {table[i,j] = (i+1) * (j+1);}
}
}
foreach (var i in table)
{
Console.write(i);
Console.Write(Environment.NewLine);
}
}
Console.Readkey();
}



 
 




 

Saturday, May 25, 2013

Write a method to find all prime numbers between 50 and 100

class Program
{
static void Main()
{
//Call the method to check for prime numbers and only print if the number is prime.
for (int x=50;  x<101 p="" x="">{
bool result = IsPrime(x);
if (result == true)
Console.Writeline("{0} is a prime number", x);
}
Console.ReadKey();
}

public static bool IsPrime(int n)
{
//negative numbers, 0 and 1 are not prime numbers
if ( n<= 1)
return false;

else
{
//you need to divide a number only by 2,3,5,7

int [] primeNumDivisors = new int[]{2,3,5,7};

foreach (int I in primeNumDivisors)
{
// no need to divide the number by itself
if ( n ! =I)
{
if (n% i ==0)
return false;
}
}
return true;
}
}
}
 


 

Tuesday, May 21, 2013

Sort Algorithms (C#)

Quick sort


The quick sort function starts its work by selecting a random value from the unsorted list. This value is called the pivot value. Then we remove the pivot value from the unsorted list.
Now each element x in the unsorted list is compared with this pivot. We have two other lists 'Less' and 'Greater'.
if any element is less than the pivot, it is placed in the 'Less' list and if it is greater than the pivot value, it is placed in the 'Greater' list. Then we call the concat function with three arguments in it.
1.List name 'Less'
2.Variable Pivot
3.List Name 'Greater

Using System;
Using System.Collection.Generic;
Using System.Linq;
Using System.Text;

namespace SortAlgorithms
{
class Quicksort
{
public List QuickSort1(List a)
{
List Less = new List();
List Greater = new List();
if (a.Count<=1)
return a;
Random R = new Random();
int pos = R.Next(0,a.Count);
int pivot = a[pos];
a.RemoveAt(pos);
foreach(int i in a)
{
if  (i < pivot)
{
Less.Add(i);
}
else
{
Greater.Add(i);
}
}
return Concat(QuickSort1(Less), pivot, QuickSort1(Greater);

 

/* The concat function here performs a very important role, the quicksort algorithm uses the recursive approach throgh concat function. 
Here concat function receives the three arguments, two lists and pivot value.  
We have defined a new list of integers here name sorted.  
It concats the less, pivot and greater all together in sorted list and then returns this sorted list to quicksort method.  
The quicksort method receives this sorted list and then returns the sorted list to the function  
which sends the unsorted list to quicksort method.*/
 
public List Concat(List Less, int pivot, List Greater)
{
List Sorted = new List(Less);
Sorted.Add(pivot);
foreach (int g in Greater)
{
Sorted.Add(g);
}
return Soretd;
}
}
}
------------------------------------------------------------------------------------------------------------

Merge Sort


Merge Sort is able to rearrange elements of a list in ascending order. Merge sort works as a divide and conquer algorithm. It recursively divide the list into two halves until one element left, and merge the already sorted halves into a sorted one list.
------------------------------------------------------------------------------------------------------------

Bubble Sort



In bubble sort, each element of the unsorted list is compared to the next element and if the value of first element is greater than the value of the second element, then they are swapped. The same is applied again and again until every element gets compared with the whole list.
The result may have ascending or descending sorted elements.The bubble sort consists on the passes. The number of passes depends on the number of elements in the list. More elements means more passes.
It consists of the two loops - a main loop and a nested loop. The main loop describes the number of passes and the nested loops defined the number of comparisons.
The bubblesort is easy to implement but it is a slow sorting algorithm. It traverses each and every element of the unsorted list in every case. That's why it has the worst case and average case complexity as 0(n2).

using System;
using System.Collection.Generic;
using System.Linq;
using System.Text;

namespace SortAlgorithms
{
class BubbleSort
{
public List BubbleSort1(List Input)
{
int temp;
for (int i =1; i < Input.Count; i++)
{
for (int j=0; j< Input.count - 1; j++)
{
if (Input[j] > Input [j+1])
{
temp =Input[j];
Input[j] = Input [j+1];
Input[j+1] = temp;
}
}
}
return Input;
}
}
}
 
 
 

 

Monday, May 20, 2013

Write a method to find how many times a substring occurs in a string (C#)


//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
namespace Excercises
{
 class Program
{
 static void Main(string[] args)
{
 //Write a method to find how many times a substring occurs in a string
string find = "and";
string input = "ROME — Italy's high court on Tuesday faulted the appeals court that acquitted American student Amanda Knox of murdering her roommate, saying its ruling was full of deficiencies, contradictions and illogical conclusions and ordering the new appeals court to look at all the evidence to determine whether Knox helped kill the teen";
char[] delimiters = { ' ', ',', '.', ';', '-' };
string[] words = input.Split(delimiters);
int count = 0;
foreach (var word in words)
{
 if (word.ToLower() == find.ToLower())
{
count++;
}
}
Console.WriteLine("The word '{0}' was found {1} times", find, count);
Console.ReadKey();
}
}
}

Wednesday, April 24, 2013

Using SQL, on a database with user logins, report the top 10 users that have logged in the most number of times in a given duration along with a count of the items created by them in that duration.

Question :
Using SQL, on a database with user logins, report the top 10 users that have logged in the most number of times in a given duration along with a count of the items created by them in that duration.
 
Example:
Using SupportDB, report the top 10 agents that have logged in the last 'n' days and the number of ServiceRequests created by each of those agents.
 
The output should look like:
 
________________________________________________
Agent Name| Last Logged Date| Log Count | SRs Created
-----------------|------------------------|----------------|---------------------
agent name | 4/20/2013T12:0.. | 23               | 109
__________|_______________|__________|____________


Solution

select UL.FullName, UL.LastLogin, temp.CountOfSRs from UserList UL
join (select top 10 SR.AuditCreatedByPuid,COUNT(SR.id) AS CountOfSRs FROM dbo.ServiceRequest SR (nolock)
where SR.AuditCreatedByPuid in (
select UL.AuditCreatedByPuid from dbo.Userlist UL
where LastLogin >= dateadd(day,- 7,GetUTCDate())
group by SR.AuditCreatedByPuid
order by CountOfSRs desc) temp on UL.PUID = temp.AuditCreatedByPuid

Saturday, April 20, 2013

Write a SQL script to convert XML data (in SQL XML data type) to a table.(SQL)

Question:

Write a SQL script to convert XML data (in SQL XML data type) to a table. Each attribute of an element in the XML should be converted to a column in the resulting table.
Example:
if the XML looks like:
...

...
then the script should produce the result as:

Table

-----------------------

attr1 | attr2 |

______|_______|

| |

value1 | value 2 |

______|_______|


Using query() and value() methods:

DECLARE @table_temp TABLE (yourXML XML)
DECLARE @xmlDoc XML

SET @xmlDoc =
(
SELECT XCol
FROM dbo.XTable WHERE ID=1
FOR XML RAW, TYPE
)
INSERT INTO @table_temp
SELECT @xmlDoc

SELECT
--t.yourXML,
--r.c.query('.'),
r.c.value('(//@PersonID)[1]', 'varchar (50)') AS PersonID,
r.c.value('(//@LastName)[1]', 'varchar(50)') AS LastName,
r.c.value('(//@PersonID)[2]', 'varchar (50)') AS PersonID,
r.c.value('(//@LastName)[2]', 'varchar(50)') AS LastName
FROM @table_temp t
CROSS APPLY t.yourXML.nodes('row') as r(c)


Using OpenXML Transact-SQL build in function

DECLARE @idoc int, @doc XML;
SET @doc =(
--You can also load a XML here from the table XML field

);
--Create an internal representation of the XML document.
EXEC sp_xml_preparedocument @idoc OUTPUT, @doc;
-- SELECT stmt using OPENXML rowset provider
SELECT *
--flag=1 is attribute centric, 2 is element centric. More info at this link : http://msdn.microsoft.com/en-us/library/ms186918(v=sql.105).aspx
FROM OPENXML (@idoc,'/row/XCol/people/person',1)
WITH (PersonID int,
LastName varchar(10)
);

Tuesday, April 9, 2013

Write a C# method to implement a change dispenser.

Question :

Write a C# method to implement a change dispenser. The change dispenser takes in a number of higher denomination and returns the smallest number of lower denominations to dispense. The method should return the denominations and the counts of those denominations.

Example: if the dispenser has $1 and $5 denominations only and the method is called with $19, then it should return 3 * $5 and 4 * $1 instead of 19 * $1 denominations as it means fewer notes. So it should return both the above denominations and their counts to the caller.

For the implementation, assume you have $1, $2, $5 and $10 denominations only, and find the least number of denominations to break a given higher denomination. Assume only whole number denominations. No need to specify '$' in the method as it is used only for representation.


Solution:
namespace Excercises
{
class Program
{
static void Main(string[] args)
{
Console.Write("Please enter the money you need the change for :");
string value = Console.ReadLine();

int TotalMoney = Int32.Parse(value);
if (TotalMoney <= 0) { Console.WriteLine("Invalid number entered. Please try again"); } if (TotalMoney > 0)
{
ChangeDispenser(TotalMoney);
}


Console.ReadKey();
}

public static void ChangeDispenser(int n)
{
//avaialble denominations $10, $5, $2, $1
int numOfTens = 0;
int numOfFives = 0;
int numOfTwos = 0;
int numOfOnes = 0;

if (n >= 10)
{
numOfTens = n / 10;
n= n%10;
}
if (n >= 5)
{
numOfFives = n / 5;
n = n % 5;
}
if (n >= 2)
{
numOfTwos = n / 2;
n = n % 2;
}
numOfOnes = n;

Console.WriteLine("Number of 10s: {0}, Number of 5s : {1}, Number of 2s : {2}, Numer of 1s : {3}", numOfTens, numOfFives, numOfTwos, numOfOnes);

}
}
}

Monday, April 8, 2013

C# Program simulating a slot machine

Question :

Write a C# program to simulate a slot machine draw. Each draw consists of 4 characters (2 alternating letters 2 numbers, like a1b2, c3x4, f5e3 etc.)

Have a method (say, 'ChaChing') which returns a random 4 characters in the above format. However, if a draw has occurred in the last 10 tries, then return a different draw.

In order for a jackpot, the draw will need to have both letters and numbers to be the same, i.e. a1a1, b4b4, h9h9 etc. Ensure that there is at least one jackpot in every 30 draws.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Collections;
namespace examples
{
    class Program
    {
        static void Main(string[] args)
        {
           
            Queue myQueue = new Queue();
 Random r = new Random();
int JackpotNumber = r.Next(30);
 for (int i = 0; i < 30; i++)
 {
     if (i == JackpotNumber)
     {
         string queueString = pattern(true);
         myQueue.Enqueue(queueString);
     }
     else
     {
         string NonJP = pattern(false);
         if (myQueue.Contains(NonJP))
         {
             string NonJP2 = pattern(false);
             myQueue.Enqueue(NonJP2);
             Console.WriteLine(NonJP2); }
         else
         {
             myQueue.Enqueue(NonJP);
             Console.WriteLine(NonJP);
         }
     }
 } Console.ReadKey();
           
            if (myQueue.Count > 30)
 {
myQueue.Dequeue();
 }
        }
        public static string pattern(bool IsJackpot)
        {
            Random random = new Random();
            int i = random.Next(9);
            int j = random.Next(9);
            string[] strArr = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
            StringBuilder str = new StringBuilder();
            if (IsJackpot)
            {
                int index = random.Next(25);
                str.Append(strArr[index]);
                str.Append(i);
                str.Append(strArr[index]);
                str.Append(i);
                return str.ToString();
            }
            else
            {
                int index = random.Next(25);
                int index1 = random.Next(25);
                if (index == index1 && i == j)
                {
                    str.Append(strArr[index + 1]);
                    str.Append(i + 1);
                    str.Append(strArr[index]);
                    str.Append(i);
                }
                else
                {
                    str.Append(strArr[index]);
                    str.Append(i);
                    str.Append(strArr[index1]);
                    str.Append(j);
                }
                return str.ToString();
            }


        }
    }
}
 

Thursday, April 4, 2013

Write a C# function to find the number of occurrences of a given word in a file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace examples
{
class Program
{
static void Main(string[] args)
{
string find = "tax";
Dictionary myDic = new Dictionary();
StreamReader InputStream = new StreamReader(@"FilePath");
StringBuilder build = new StringBuilder();
build.Append(InputStream.ReadToEnd());
string[] strArr = build.ToString().Split(' ');
for (int i = 0; i < strArr.Length; i++)
{
if (strArr[i].ToLower() == find.ToLower())
{
if (myDic.ContainsKey(find.ToLower()))
{
myDic[strArr[i]]++;
}
else
{
myDic.Add(find.ToLower(), 1);
}
}
}
foreach (var v in myDic)
{
Console.WriteLine("'{0}' occurs {1} times in the input file", find, v.Value);
}
Console.ReadKey();
}
}
}

Friday, February 15, 2013

Describe the difference between a Thread and a Process? Write an example to create both. (C#)

Threads vs Processes

A thread is analogous to the operating system process in which your application runs. Just as processes run in parallel on a computer, threads run in parallel within a single process. Processes are fully isolated from each other; threads have just a limited degree of isolation. In particular, threads share (heap) memory with other threads running in the same application. This, in part, is why threading is useful: one thread can fetch data in the background, for instance, while another thread can display the data as it arrives.

A great tutorial on threads and its implementations is :
http://www.albahari.com/threading/

What is an interface? When would you use an interface vs. an abstract class? (C#)

What is an Abstract Class?

An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

What is an Interface?

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn’t support multiple inheritance, interfaces are used to implement multiple inheritance.

Both Together

When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.
When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.
There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison:


Feature Interface Abstract Class
Multiple inheritance A class may inherit several interfaces. A class may inherit only one abstract class.
Default implementation An interface cannot provide any code, just the signature. An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access Modifiers An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public An abstract class can contain access modifiers for the subs, functions, properties
Core VS Peripheral Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface. An abstract class defines the core identity of a class and there it is used for objects of the same type.
Homogeneity If various implementations only share method signatures then it is better to use Interfaces If various implementations are of the same kind and use common behavior or status then abstract class is better to use.
Speed Requires more time to find the actual method in the corresponding classes. Fast.
Adding functionality (Versioning) If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method. If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and Constants No fields can be defined in interfaces An abstract class can have fields and constraints defined