Tuesday, July 31, 2012

Find The Largest Palindrome Lesser Than The Given Number 'N' - O(Log(N)) base 10

Problem:
Given a number "N", find out a number "k" such that 'k' is the largest palindrome that is lesser than "N". [Even when given number is a palindrome]
e.g. if N if 64 print 55, if N=320 Print 313.

Analysis & Algorithm:
For our simplicity we will create an integer array from the given number. This array will save each digit as its element.Lets write IsPalindrome method such that it accepts this integer array and determines whether number is already a palindrome.

We need to understand that while we are doing any swap or interchange or modification, resultant number should not go greater than given number itself.

If second half of the array is mirror image of numbers in first half of the array around mid point, then we can say that is a palindrome. Do not even try decreasing the number in a loop and keep checking whether the reduced number is a palindrome. That certainly is a bad approach.

Lets try anther approach where we make second half of the array as the mirror image of first half of array. For this we can copy numbers in the 'i'th position of array into 'array.length -i'th position. This would assure we will get a palindrome number.

But, wait, this would not give what is asked for. We need to find a number which is strictly lesser than given number and the largest of all palindromes under it.

Lets iterate from i=0 to i<=len/2, where len is the number of digits in the given number.

If we handle few cases then we can improve above mentioned solution to work for us:

1. When a[i] > a[len-i], then we cannot simply copy a[len-i] = a[i], this will make the number greater than given number. This case can be handled like subtraction of a larger digit from a smaller digit, where we take the carry from next digit. Similarly when a[i]>a[len-i], we will try to take the carry from the next digit i.e. a[len-i-1]. If that digit is a zero, we will proceed till we get a non zero integer and then carry from it. i.e. reduce that non zero number in the array by 1 and then make all zeros on the way to 9. This is same like in subtraction again. Once this is done we can copy the value a[i] into a[len-i].

2. If a[i]<a[len-i], directly copy a[i] into a[len-i]

3. If the number itself is a palindrome, reduce the number by 1 and apply the same algorithm as above.


If you take care of indexes properly above algorithm should work you in all the cases. C# Code for above explained solution is below. Comment if you have a suggestion or if you find a problem in my approach.


Solution:



        public static void GetLargestPalindromeLesserThan(int[] num)
        {
            int len = num.Length - 1;
            //check if its already a palindrome, then we will alter the number as 1 as given input
            if(isPalindrome(num))
            {
                int k =0;
                while (num[len - k] == 0)
                {
                    num[len - k] = 9; ;
                    k++;
                }
                num[len - k]--;
            }
            for (int i = 0; i <= len / 2; i++)
            {


                if (i != (len - i))
                {
                    if (num[i] > num[len - i])
                    {

                        int k = 1;
                        while (num[len - i - k] == 0 && (len - i - k) != i)
                        {
                            //same as taking a carry and moving it to next digit
                            num[len - i - k] = 9;
                            k++;
                        }
                        num[len - i - k]--;
                        num[len - i] = num[i];
                    }


                    else
                    {
                        num[len - i] = num[i];
                    }
                }
                
            }
            for (int i = 0; i <= len; i++)
            {
                Console.Write(num[i]);
            }
        }


        private static bool isPalindrome(int[] num)
        {
            int len = num.Length - 1;
            for (int i = 0; i < len / 2; i++)
            {
                if (num[i] != num[len - i])
                {
                    return false;
                }
            }
            return true;
        }


Thursday, July 19, 2012

Reverse words of a given string - In place C# function without using string operations

Problem:

Given a string like "No, I'm Not Manu M S" print the words of the string in reverse order. Output: "S M Manu Not I'm No,". Do not use another string or stack or extra storage for doing this.

Solution:

We will write plain C style code without using any C# string method. Lets assume, words are separated by a space. Lets ignore the case wherever other symbols can separate the words( for our simplicity). We are asked to reverse the words but not the string reversal itself.

Our method follows below steps,

1. Find the length of a string. Bear with me to use Length property of string, since it is straight forward , lets not even code how to find the length also.

2. Reverse the string in-place, for each character in string from 0 to length/2 swap character at [length - i] with character at [i]. Remember to exit this loop at length/2, otherwise string gets reversed again. i.e. after length/2 steps we will have the reversed string with us.

3. For each word in the reversed string, reverse the characters. This step is not O(n) since we loop for the letters of a word inside the loop which loops through each character of reversed string. Inner loop is to reverse letters of each word of the reversed string. Make sure indexes are incremented carefully, to consider index of space, last index of space etc.

4. Print the string now. We have the words reversed.


Code:

       public static void ReverseWords(char[] words)
        {
            //O(n)
            int lenght = words.Length - 1;
            char temp ='o'; 

            //O(n/2)
            for (int i = 0; i <= lenght/2; i++)
            {
                //swap char at n-i with i
                temp = words[i];
                words[i] = words[lenght - i];
                words[lenght - i] = temp;
            }

            int wordStartIndex = 0;
            int wordEndIndex = 0;
            for (int i = 0; i <= lenght; i++)
            {
                if (words[i] == ' '  || i== lenght)
                {
                    //special care for last word
                    if (i != lenght)
                        wordEndIndex = i - 1;
                    else
                        wordEndIndex = lenght;
                    for (int j = wordStartIndex; j <= (wordStartIndex + wordEndIndex) / 2; j++)
                    {
                        //swap char at n-i with i
                        
                        temp = words[j];
                        words[j] = words[wordEndIndex + wordStartIndex- j];
                        words[wordEndIndex + wordStartIndex - j] = temp;
                    }
                    wordStartIndex = i + 1;
                }
            }

            //print the reversed words in given string
            for (int i = 0; i <= lenght; i++)
            {
                Console.Write(words[i]);
            }
            Console.WriteLine();
        }

Thursday, July 12, 2012

Algorithm to move all ones(1's) in an array to end of the array - O(n) Solution

Problem:
Given an array which contains only 0's and 1's. Write an algorithm to move all the 1's in the array to end of the array in one traversal only. Avoid unnecessary swapping and using extra space.

Different version of this problem would be Dutch National Flag Problem, which is very common question in many interviews in initial stages. Above given problem is simplified version of 0, 1, 2 or Dutch Flag problem, where we are concerned only about moving 0's to initial parts of the given array. We keep track of index of zeroes(i.e. nothing but number of zeroes that we have encountered till now), whenever we find zero in the array we swap with this zero index that we have been tracking.

Solution:
Below code in C#, I think code itself is self explanatory. If not drop a comment please.

========================================================================

           int[] arr = { 1, 0, 1, 0, 1, 0, 1, 0, 1};


            int zeroIndex = 0;
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i] == 0)
                {
                    if (i!= zeroIndex && arr[i] != arr[zeroIndex])
                    {
                        int temp = arr[i];
                        arr[i] = arr[zeroIndex];
                        arr[zeroIndex] = temp;
                    }
                        zeroIndex++;
                    
                }
            }


            for (int i = 0; i < arr.Length; i++)
            {
                Console.Write(arr[i]);
            }
========================================================================

Tuesday, July 10, 2012

Hooking Mouse and Keyboard, Marshaling and few user32 library methods call in C#



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;

namespace WindowsFormsApplication1
{

    [Flags]
    public enum SendMessageTimeoutFlags : uint
    {
        SMTO_NORMAL = 0x0,
        SMTO_BLOCK = 0x1,
        SMTO_ABORTIFHUNG = 0x2,
        SMTO_NOTIMEOUTIFNOTHUNG = 0x8
    }
    public partial class Form1 : Form
    {

        public delegate int HookProc(int code, IntPtr wparam, IntPtr lparam);
        static int hHook = 0;
        static int mHook = 0;
        IntPtr windowHandle;
        uint processHandle;

        int WH_MOUSE = 7;
        int WH_KEYBOARD = 2;
        static int HC_ACTION = 0;
        static int VK_CONTROL = 11;

        //This is the Import for the SetWindowsHookEx function.
        //Use this function to install a thread-specific hook.
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);

        //This is the Import for the UnhookWindowsHookEx function.
        //Call this function to uninstall the hook.
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern bool UnhookWindowsHookEx(int idHook);

        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern IntPtr GetForegroundWindow();


        [DllImport("user32.dll")]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

        //This is the Import for the CallNextHookEx function.
        //Use this function to pass the hook information to the next hook procedure in chain.
        [DllImport("user32.dll", CharSet = CharSet.Auto,CallingConvention = CallingConvention.StdCall)]
        public static extern int CallNextHookEx(int idHook, int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern short GetAsyncKeyState(int vkey);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int GetLastError();


        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern IntPtr FindWindow(string classname, string windowName);

        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern IntPtr SendMessage(IntPtr hWnd,uint Msg,IntPtr wParam,IntPtr lParam);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern IntPtr SendMessageTimeout(
            IntPtr hWnd,
            uint Msg,
            UIntPtr wParam,
            IntPtr lParam,
            SendMessageTimeoutFlags fuFlags,
            uint uTimeout,
            out UIntPtr lpdwResult);

        HookProc MouseHookProcDel;
        HookProc KeyBoardHookProcDel;

        [StructLayout(LayoutKind.Sequential)]
        public class POINT
        {
            public int x;
            public int y;
        }

        //Declare the wrapper managed MouseHookStruct class.
        [StructLayout(LayoutKind.Sequential)]
        public class MouseHookStruct
        {
            public POINT pt;
            public int hwnd;
            public int wHitTestCode;
            public int dwExtraInfo;
        }

        //to marshal to lparam of keyboard hook into a manage type
        [StructLayout(LayoutKind.Sequential)]
        public class KBDLLHOOKSTRUCT
        {
            public uint vkCode;
            public uint scanCode;
            public uint flags;
            public uint time;
            public uint dwExtraInfo;
        }

        public Form1()
        {
            InitializeComponent();
        }


        public static int MouseHookProcedure(int code, IntPtr wparam, IntPtr lparam)
        {
            MouseHookStruct mouse = (MouseHookStruct)Marshal.PtrToStructure(lparam, typeof(MouseHookStruct));
       
            if(code == 0)
            {
                //Create a string variable that shows the current mouse coordinates.
                String strCaption = "x = " +
                        mouse.pt.x.ToString("d") +
                            "  y = " +
                mouse.pt.y.ToString("d");
                //You must get the active form because it is a static function.
                Form tempForm = Form.ActiveForm;

                //Set the caption of the form.
                tempForm.Text = strCaption;
                return CallNextHookEx(hHook, code, wparam, lparam);
            }
            else
                //calls the next hook with same message and parameters
                return CallNextHookEx(hHook, code, wparam, lparam);
        }

        public static int KeyBoardProcedure(int code, IntPtr wparam, IntPtr lparam)
        {
           //KBDLLHOOKSTRUCT's structure is copied as it is from msdn to support marshaling
            KBDLLHOOKSTRUCT pkbhs = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lparam, typeof(KBDLLHOOKSTRUCT));
            int bControlKeyDown = 0 ;
            switch (code)
            {
                //0 refers to HC_ACTION
                case 0:
                    {
                        // Check to see if the CTRL key is pressed
                        bControlKeyDown = GetAsyncKeyState(VK_CONTROL) >> ((sizeof(short) * 8) - 1);

                       //write to logic to handle ctrl+esc or alt+tab or any other key here
                       //then return 1               
                        break;
                    }

                default:
                    return CallNextHookEx(mHook, code, wparam, lparam);
                   
            }
            return CallNextHookEx(mHook, code, wparam, lparam);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (hHook == 0 && mHook==0)
            {
                // Create an instance of HookProc.
                MouseHookProcDel = new HookProc(Form1.MouseHookProcedure);
                KeyBoardHookProcDel = new HookProc(Form1.KeyBoardProcedure);

                hHook = SetWindowsHookEx(WH_MOUSE,
                            MouseHookProcDel,
                            (IntPtr)0,
                            AppDomain.GetCurrentThreadId());

                mHook = SetWindowsHookEx(WH_KEYBOARD,
                            KeyBoardHookProcDel,
                            (IntPtr)0,
                            AppDomain.GetCurrentThreadId());
                //If the SetWindowsHookEx function fails.
                if (hHook == 0)
                {

                    MessageBox.Show("SetWindowsHookEx Failed" + ":" + GetLastError().ToString());
                    return;
                }
                button1.Text = "UnHook Windows Hook";
            }
            else
            {
                bool ret = UnhookWindowsHookEx(hHook);
                ret = UnhookWindowsHookEx(mHook);
                //If the UnhookWindowsHookEx function fails.
                if (ret == false)
                {
                    MessageBox.Show("UnhookWindowsHookEx Failed");
                    return;
                }
                hHook = 0;
                mHook = 0;
                button1.Text = "Hook Mouse and Keyboard";
                this.Text = "Mouse Hook";
            }
        }

        private void GetActiveWindowTitle()
        {          
            const int nChars = 256;
            IntPtr handle = IntPtr.Zero;
            StringBuilder Buff = new StringBuilder(nChars);
            handle = GetForegroundWindow();

            if (GetWindowText(handle, Buff, nChars) > 0)
            {
                MessageBox.Show(Buff.ToString());

            }
            return;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //on timer elapsed, we get the active window's title
            // uncomment to use it
            //GetActiveWindowTitle();
        }

        private void CheckWhetherProcessIsHung()
        {
           //easy way of doing this would be to check process.Responding attribute
           //C# makes it totally easy with Process class

            //edit is the class name here for Notepad
            IntPtr hwnd = FindWindow("Edit", null);
            UIntPtr let;

            //Aborts if the process to which we are sending message fails
            IntPtr result =  SendMessageTimeout(hwnd, 0, (UIntPtr)0, (IntPtr)0, SendMessageTimeoutFlags.SMTO_ABORTIFHUNG, 15000, out let);
           
            //there will be error if result = 0, get last error and show it then
            if (result == (IntPtr)0)
                MessageBox.Show(GetLastError().ToString());
        }

        private void button2_Click(object sender, EventArgs e)
        {
            CheckWhetherProcessIsHung();
        }
    }
}


References:
Pinvoke.net , msdn dev center -desktop and microsoft support pages

Tuesday, July 3, 2012

Non-Recursive (Morris) In-Order Traversal and Recursive In-Order Traversal in C#

Morris In-Order traversal traverses the given tree in in-order without using Recursion or Stack. Morris In-Order traversal uses concept of threading the nodes, which are either leaves or which do not have right node to their in-order successors. This allows traversing back in in-order hierarchy simple. Traversal also removes the links that are created for this purpose and keep the tree unchanged.

Steps involved in Morris traversal are:

1. Get the in-order predecessor of current node: In-order successor of any given node in BST is a node's left node's right most element.

2. When you reach such in-order predecessor for current node, since that node will be either be a leaf node or a node that does not have right child. Make current as right child of that in-order predecessor and move current node pointer to its left item.

3. A temporary pointer "pre" is used to find out the in-order predecessor of given node "current". "pre.Right = current; " is used to thread in-order predecessor node to its successor.

4. When current moves to the left most element in the tree, print the data of the node and move current to current's right. This is important. It uses previously created link to move to in-order successor of current.

5. Then to remove this link, we follow finding in-order predecessor procedure until pre-Right points to current node itself. That means there is a link between current and the node "pre" is pointing to. Since we have already visited that node, we shall break this link, by setting pre.Right = null. We also shall print this "current" node data and then move to its in-order successor using the links that we created in earlier steps.

6. When pre.Right == Current means  there is a link that we created between pre and current. We shall break link and proceed to next in-order successor using Current = current.Right;

7. Also Current = current.Right when (pre.Right== current) assures that after left tree is processed, we move right part of the given binary search tree.

8. When Current moves to left most node of the tree, i.e. if Current.Left == null then Current= current.Right assures we traverse back to its in-order successor using the link that we already created.


Below code also includes a method which does recursive in-order traversal in order to compare with Morris traversal.

Complete Code:
=======================================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            Node root = new Node();
            root.Data = 6;
            root.Left = new Node(4);
            root.Left.Right = new Node(5);
            root.Right = new Node(10);
            root.Left.Left = new Node(2);
            root.Left.Left.Left = new Node(1);
            root.Right.Left = new Node(8);
            root.Right.Left.Right = new Node(9);
            root.Right.Left.Left = new Node(7);
            root.Right.Right = new Node(14);
            root.Right.Right.Left = new Node(13);
            root.Right.Right.Left.Left = new Node(12);
            root.Right.Right.Right = new Node(17);


            PrintInorderTraversal(root);
            Console.WriteLine("");
            Add(root, 3);
            Add(root, 11);


            PrintInorderTraversal(root);
            Console.WriteLine("");
            Console.WriteLine("morris inorder travesal using threading");
            Console.WriteLine("");
            MorrisInorderTraversal(root);
            Console.ReadLine();




        }


        static void MorrisInorderTraversal(Node root)
        {
            Node current = root;
            Node pre = null;
            while (current != null)
            {
                //it is looping back to parent
                //using already threaded leaf and node in hierarchy
                if (current.Left == null)
                {
                    Console.Write(current.Data + " ");
                    current = current.Right;
                }
                else
                {
                    //now find the inorder predeccsor or current node
                    pre = current.Left;
                    while (pre.Right != null && pre.Right != current)
                    {
                        pre = pre.Right;
                    }
                    if (pre.Right == null)
                    {
                        //inorder predeccesor found
                        //move current to left again
                        pre.Right = current;
                        current = current.Left;
                    }
                    else
                    {
                        //after every thread is been created from a node which does not have a right node
                        //to its inorder successor
                        //now lets visit that inorder successor using right pointer


                        //lets print the data and move to right i.e go up to inorder successor                        
                        pre.Right = null;
                        Console.Write(current.Data+" ");
                        current = current.Right;
                    }


                }
            }
        }
        static void PrintInorderTraversal(Node current)
        {
            if (current != null)
            {
                PrintInorderTraversal(current.Left);
                Console.Write(current.Data+" ");
                PrintInorderTraversal(current.Right);
            }
        }


        static void Add(Node root, int data)
        {
            Node current = root; Node Parent = null;
            Node temp = new Node(data);
            while (current != null)
            {
                if (current.Data > data)
                {
                    Parent = current;
                    current = current.Left;
                }
                else if(current.Data < data)


                {
                    Parent = current;
                    current = current.Right;
                }
                else
                {
                    //duplicte value
                    return;
                }               
            }
            //empty tree
            if (Parent == null)
            {
                root = temp;
            }
            else
            {


                if (Parent.Data > data)
                {
                    Parent.Left = temp;
                }
                else
                {
                    Parent.Right = temp;
                }
            }
        }
    }


    public class Node
    {
        int data;


        public Node()
        {
        }


        public int Data
        {
            get { return data; }
            set { data = value; }
        }
        Node left = null;


        public Node Left
        {
            get { return left; }
            set { left = value; }
        }


        Node right =null;


        public Node Right
        {
            get { return right; }
            set { right = value; }
        }


        public Node(int v)
        {
            data = v;
        }        
    }
}
=======================================================================


Reference & Thanks: GeeksForGeeks.org