Wednesday, June 12, 2013

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