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);