Esempio n. 1
0
 public override void Run()
 {
     int[] array = AssortedMethods.RandomArray(10, -10, 10);
     Console.WriteLine(AssortedMethods.ArrayToString(array));
     SwapMinMaxBetter(array);
     Console.WriteLine(AssortedMethods.ArrayToString(array));
 }
Esempio n. 2
0
        public void Run()
        {
            Push(0, 10);
            Push(1, 20);
            Push(2, 30);

            Push(1, 21);
            Push(0, 11);
            Push(0, 12);

            Pop(0);

            Push(2, 31);

            Push(0, 13);
            Push(1, 22);

            Push(2, 31);
            Push(2, 32);
            Push(2, 33);
            Push(2, 34);

            Console.WriteLine("Final Stack: " + AssortedMethods.ArrayToString(_buffer));

            Pop(1);
            Push(2, 35);

            Console.WriteLine("Final Stack: " + AssortedMethods.ArrayToString(_buffer));
        }
Esempio n. 3
0
        /// <summary>
        /// Where bit traker 'checker' will store/set bit for each charecter
        /// and when upon 1&1 it indiacate that charecter already exists.
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsUniqueChars_UsingBitTracker(string str)
        {
            string prefix = "IsUniqueChars_UsingBitTracker: ";

            Console.WriteLine($"{prefix} str={str}");
            if (str.Length > 256)
            {
                return(false);
            }
            var checker = 0;

            for (var i = 0; i < str.Length; i++)
            {
                var val = str[i] - 'a';
                Console.WriteLine($"{prefix} str[i]=" + str[i]);
                //Console.WriteLine($"{prefix}  val= (str[i] - 'a') = {str[i] - 'a'} =" + val);
                Console.WriteLine($"{prefix}  checker= {checker} [{AssortedMethods.ToFullBinarystring(checker)}]");
                Console.WriteLine($"{prefix}  (1 << val)=(1 [{AssortedMethods.ToFullBinarystring(1)}] << {val}) = {(1 << val)} [{AssortedMethods.ToFullBinarystring((1 << val))}]");
                Console.WriteLine($"{prefix}  (checker & (1 << val)) > 0 = [{AssortedMethods.ToFullBinarystring(checker)}] & [{AssortedMethods.ToFullBinarystring((1 << val))}] = [{AssortedMethods.ToFullBinarystring((checker & (1 << val)))}] > 0 = " + ((checker & (1 << val)) > 0));
                if ((checker & (1 << val)) > 0)
                {
                    Console.WriteLine($"{prefix} Return False");
                    return(false);
                }
                Console.WriteLine($"{prefix}  checker |= (1 << val) =  [{AssortedMethods.ToFullBinarystring(checker | (1 << val))}]" + (checker | (1 << val)));
                checker |= (1 << val);
            }
            return(true);
        }
        public void Test()
        {
            const int size = 5;

            int[] list = AssortedMethods.RandomArray(size, -5, 5);
            foreach (int t in list)
            {
                Track(t);
            }

            var tracker = new int[size];

            foreach (int t in list)
            {
                int v     = t;
                int rank1 = _root.GetRank(t);
                tracker[rank1] = v;
            }

            for (int i = 1; i < tracker.Length; i++)
            {
                if (tracker[i] == 0 || tracker[i - 1] == 0)
                {
                    continue;
                }

                if (tracker[i] > tracker[i - 1])
                {
                    Console.WriteLine("ERROR at " + i);
                }
            }

            Console.WriteLine("Array: " + AssortedMethods.ArrayToString(list));
            Console.WriteLine("Ranks: " + AssortedMethods.ArrayToString(tracker));
        }
        public void Run1()
        {
            int M      = 10;
            int N      = 5;
            var matrix = new int[M, N];

            for (int i = 0; i < M; i++)
            {
                for (int j = 0; j < N; j++)
                {
                    matrix[i, j] = 10 * i + j;
                }
            }

            AssortedMethods.PrintMatrix(matrix);

            for (int i = 0; i < M; i++)
            {
                for (int j = 0; j < M; j++)
                {
                    int v = 10 * i + j;
                    Console.WriteLine(v + ": " + FindElement(matrix, v));
                }
            }
        }
Esempio n. 6
0
    public static void QuestionsAndSolutionsByChapters()
    {
        var chapters = new[]
        {
            //// Intro
            //new IQuestion[] { new CompareBinaryToHex(), new SwapMinMax(), },

            //// Chapters
            new IQuestion[] {
                new Array_Q1_01_Is_String_Has_Unique_Chars(),
                //,  new Q1_02_Check_Permutation(), new Q1_03_URLify(), new Q1_04_Palindrome_Permutation(), new Q1_05_One_Away_A(), new Q1_06_String_Compression(), new Q1_07_Rotate_Matrix(), new Q1_08_Zero_Matrix(), new Q1_09_String_Rotation(),
            },

            //new IQuestion[] { new Q2_01_Remove_Dups(), new Q2_02_Return_Kth_To_Last(), new Q2_03_Delete_Middle_Node(), new Q2_04_Partition(), new Q2_05_Sum_Lists(), new Q2_06_Palindrome(), new Q2_07_Intersection(), new Q2_08_Loop_Detection() },

            //new IQuestion[] { new Q5_01_Insertion(), new Q5_02_Binary_to_String(), new Q5_04_Next_Number(), new Q5_06_Conversion(), new Q5_06_Conversion(), new Q5_07_Pairwise_Swap(), new Q5_08_Draw_Line() },

            //new IQuestion[] { new Q10_01_Sorted_Merge(), new Q10_02_Group_Anagrams(), new Q10_03_Search_in_Rotated_Array(), new Q10_05_Sparse_Search(), new Q10_08_Find_Duplicates(), new Q10_09_Sorted_Matrix_Search(), new Q10_10_Rank_from_Stream(), new Q10_11_Peaks_and_Valleys() },
        };

        foreach (var chapter in chapters)
        {
            foreach (IQuestion q in chapter)
            {
                Console.WriteLine(string.Format("{0}{1}", Environment.NewLine, Environment.NewLine));
                AssortedMethods.PrintType(q);
                q.Run();
            }

            Console.WriteLine();
            Console.WriteLine("Press Enter to continue..");
            //Console.ReadLine();
        }
    }
Esempio n. 7
0
File: Q03_6.cs Progetto: zs9912/ctci
 public void Run()
 {
     for (int k = 1; k < 10; k++)
     {
         _c = 0;
         Stack <int> s = new Stack <int>();
         for (int i = 0; i < 10 * k; i++)
         {
             int r = AssortedMethods.RandomIntInRange(0, 1000);
             s.Push(r);
         }
         s = Mergesort(s);
         int last = int.MaxValue;
         while (s.Count != 0)
         {
             int curr = s.Pop();
             if (curr > last)
             {
                 Console.WriteLine("Error: " + last + " " + curr);
             }
             last = curr;
         }
         Console.WriteLine(_c);
     }
 }
Esempio n. 8
0
        public override void Run()
        {
            int size = 100;

            int[] list = AssortedMethods.RandomArray(size, -100, 100);
            for (int i = 0; i < list.Length; i++)
            {
                Track(list[i]);
            }

            int[] tracker = new int[size];
            for (int i = 0; i < list.Length; i++)
            {
                int v     = list[i];
                int rank1 = root.GetRank(list[i]);
                tracker[rank1] = v;
            }

            for (int i = 0; i < tracker.Length - 1; i++)
            {
                if (tracker[i] != 0 && tracker[i + 1] != 0)
                {
                    if (tracker[i] > tracker[i + 1])
                    {
                        Console.WriteLine("ERROR at " + i);
                    }
                }
            }

            Console.WriteLine("Array: " + AssortedMethods.ArrayToString(list));
            Console.WriteLine("Ranks: " + AssortedMethods.ArrayToString(tracker));
        }
Esempio n. 9
0
 public override void Run()
 {
     int[] a = new int[] { 2, 3, 4, 5, 6, 8, 10, 100, 0, 0, 0, 0, 0, 0 };
     int[] b = new int[] { 1, 4, 7, 6, 7, 7 };
     Merge(a, b, 8, 6);
     Console.WriteLine(AssortedMethods.ArrayToString(a));
 }
        public void Run2()
        {
            int[,] matrix = new[, ] {
                { 15, 30, 50, 70, 73 },
                { 35, 40, 100, 102, 120 },
                { 36, 42, 105, 110, 125 },
                { 46, 51, 106, 111, 130 },
                { 48, 55, 109, 140, 150 }
            };

            AssortedMethods.PrintMatrix(matrix);

            int rows    = matrix.GetLength(0);
            int columns = matrix.GetLength(1);

            int count            = 0;
            int littleOverTheMax = matrix[rows - 1, columns - 1] + 10;

            for (int i = 0; i < littleOverTheMax; i++)
            {
                Coordinate c = FindElement2(matrix, i);
                if (c != null)
                {
                    Console.WriteLine(i + ": (" + c.row + ", " + c.column + ")");
                    count++;
                }
            }
            Console.WriteLine("Found " + count + " unique elements.");
        }
            /// <summary>
            /// Using HashMapList/Dictionary
            /// </summary>
            /// <param name="array"></param>
            public static void Sort_GroupWordsByAnagram_UsingDictionary(string[] array)
            {
                Console.WriteLine(AssortedMethods.StringArrayToString(array));
                Dictionary <string, LinkedList <string> > hash = new Dictionary <string, LinkedList <string> >();

                /* Group words by anagram */
                foreach (string s in array)
                {
                    string key = SortChars(s);
                    if (!hash.ContainsKey(key))
                    {
                        hash.Add(key, new LinkedList <string>());
                    }
                    LinkedList <string> anagrams = hash[key];
                    anagrams.AddLast(s);
                }

                /* Convert hash table to array */
                int index = 0;

                foreach (string key in hash.Keys)
                {
                    LinkedList <string> list = hash[key];
                    foreach (string t in list)
                    {
                        array[index] = t;
                        index++;
                    }
                }

                Console.WriteLine(AssortedMethods.StringArrayToString(array));
            }
Esempio n. 12
0
        /// <summary>
        /// Requires no additional memory if used proper sorting algorithms (-which does not require additional memory)
        /// </summary>
        /// <param name="str1"></param>
        /// <param name="str2"></param>
        /// <returns></returns>
        public static bool CheckIfStringsArePermutaion_1_UsingSort(string str1, string str2)
        {
            AssortedMethods.PrintType(type: typeof(StringUtility), methodName: nameof(CheckIfStringsArePermutaion_1_UsingSort));

            if (str1.Length != str2.Length)
            {
                Console.WriteLine($"Length of '{str1}' does not match with {str2}");
                return(false);
            }

            var originalAsArray = str1.ToCharArray();

            // Array.Sort Is Default Implementaion.
            // It should be implementted using quick sort see sorting.cs for quick sort exampled
            Array.Sort(originalAsArray);
            //Console.WriteLine($"'{str1}' after sort {new string(originalAsArray)}");
            str1 = new string(originalAsArray);

            var valueToTestAsArray = str2.ToCharArray();

            // Array.Sort Is Default Implementaion.
            // It should be implementted using quick sort see sorting.cs for quick sort exampled
            Array.Sort(valueToTestAsArray);
            //Console.WriteLine($"'{str2}' after sort {new string(valueToTestAsArray)}");
            str2 = new string(valueToTestAsArray);

            Console.WriteLine($" Is '{str1}' and {str2} are permutaion-{str1.Equals(str2)}");
            //Console.WriteLine("===================================================================================");
            return(str1.Equals(str2));
        }
Esempio n. 13
0
File: Q01_7.cs Progetto: zs9912/ctci
        public void Run()
        {
            int nrows = 10;
            int ncols = 15;

            int[][] matrix1 = AssortedMethods.RandomMatrix(nrows, ncols, 0, 100);
            int[][] matrix2 = CloneMatrix(matrix1);

            AssortedMethods.PrintMatrix(matrix1);

            SetZeros(matrix1);
            SetZeros2(matrix2);

            Console.WriteLine();

            AssortedMethods.PrintMatrix(matrix1);
            Console.WriteLine();
            AssortedMethods.PrintMatrix(matrix2);

            if (MatricesAreEqual(matrix1, matrix2))
            {
                Console.WriteLine("Equal");
            }
            else
            {
                Console.WriteLine("Not Equal");
            }
        }
Esempio n. 14
0
        public void Run()
        {
            for (var k = 1; k < 10; k++)
            {
                _c = 0;
                var stack = new Stack <int>();

                for (var i = 0; i < 10 * k; i++)
                {
                    var randomNum = AssortedMethods.RandomIntInRange(0, 1000);
                    stack.Push(randomNum);
                }

                stack = Mergesort(stack);
                var last = int.MaxValue;

                while (stack.Count != 0)
                {
                    var curr = stack.Pop();

                    if (curr > last)
                    {
                        Console.WriteLine("Error: " + last + " " + curr);
                    }
                    last = curr;
                }

                Console.WriteLine(_c);
            }
        }
Esempio n. 15
0
File: Q02_3.cs Progetto: zs9912/ctci
        public void Run()
        {
            LinkedListNode head = AssortedMethods.RandomLinkedList(10, 0, 10);

            Console.WriteLine(head.PrintForward());
            DeleteNode(head.Next.Next.Next.Next); // delete node 4
            Console.WriteLine(head.PrintForward());
        }
Esempio n. 16
0
        public void Run()
        {
            int[] nodesFlattened = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            var   root           = AssortedMethods.CreateTreeFromArray(nodesFlattened);
            var   list           = CreateLevelLinkedList(root);

            PrintResult(list);
        }
Esempio n. 17
0
            public void Run()
            {
                var a = 103217;

                Console.WriteLine(a + ": " + AssortedMethods.ToFullBinarystring(a));
                var b = SwapOddEvenBits(a);

                Console.WriteLine(b + ": " + AssortedMethods.ToFullBinarystring(b));
            }
Esempio n. 18
0
        public int ClearBit(int number, int i)
        {
            int mask = ~(1 << i);

            Console.WriteLine($"ClearBit:(number({number})={AssortedMethods.ToFullBinarystring(number, 4)}) " +
                              $"& mask({mask})={AssortedMethods.ToFullBinarystring(mask, 4)})={(number & mask)}         " +
                              $"mask= ~(1 << {i})=~[{AssortedMethods.ToFullBinarystring(1 << i, 4)}] =[{AssortedMethods.ToFullBinarystring(~(1 << i), 4)}]={mask}");
            return(number & mask);
        }
 public void Run()
 {
     AssortedMethods.PrintLine('-', "Sort_GroupWordsByAnagram_UsingCustomAnagramComparator");
     string[] array = { "apple", "banana", "carrot", "ele", "duck", "papel", "tarroc", "cudk", "eel", "lee" };
     Sort_GroupWordsByAnagram_UsingCustomAnagramComparator(array);
     AssortedMethods.PrintLine('-', "Sort_GroupWordsByAnagram_UsingDictionary");
     string[] array2 = { "apple", "banana", "carrot", "ele", "duck", "papel", "tarroc", "cudk", "eel", "lee" };
     Sort_GroupWordsByAnagram_UsingDictionary(array2);
 }
        public void Run()
        {
            var head = AssortedMethods.RandomLinkedList(10, 0, 10);

            Console.WriteLine(head.PrintForward());

            head = ReverseList(head);
            Console.WriteLine(head.PrintForward());
        }
Esempio n. 21
0
        /// <summary>
        /// clear all right to ith position
        /// </summary>
        /// <param name="number"></param>
        /// <param name="i"></param>
        /// <returns></returns>
        public int ClearBitsMSBthroughtI_RightRemova(int number, int i)
        {
            int mask = (1 << i) - 1;

            Console.WriteLine($"ClearBitsMSBthroughtI:(number({number})={AssortedMethods.ToFullBinarystring(number, 4)}) " +
                              $"& mask({mask})={AssortedMethods.ToFullBinarystring(mask, 4)})={(number & mask)}          " +
                              $"mask= ((1 << i) - 1)=(1 << i) [{AssortedMethods.ToFullBinarystring(1 << i, 4)}]-1 [{AssortedMethods.ToFullBinarystring(-1, 4)}]=[{AssortedMethods.ToFullBinarystring((1 << i) - 1, 4)}]={mask}" +
                              $"");
            return(number & mask);
        }
Esempio n. 22
0
        public void Run()
        {
            const int size = 3;

            int[][] matrix = AssortedMethods.RandomMatrix(size, size, 0, 9);
            AssortedMethods.PrintMatrix(matrix);
            Rotate(matrix, size);
            Console.WriteLine();
            AssortedMethods.PrintMatrix(matrix);
        }
Esempio n. 23
0
        /// <summary>
        /// Used for unicodes charctes
        /// </summary>
        /// <param name="str1"></param>
        /// <param name="str2"></param>
        /// <returns></returns>
        public static bool CheckIfStringsArePermutaion_3_UsingHashtable(string str1, string str2)
        {
            AssortedMethods.PrintType(type: typeof(StringUtility), methodName: nameof(CheckIfStringsArePermutaion_3_UsingHashtable));
            if (str1.Length != str2.Length)
            {
                //Console.WriteLine($"Length of '{str1}' does not match with {str2}");
                return(false);
            }

            Hashtable hashtable       = new Hashtable();
            var       originalAsArray = str1.ToCharArray();

            originalAsArray.Print($"'{str1}'- original.ToCharArray():");

            foreach (var character in originalAsArray)
            {
                if (hashtable.ContainsKey(character))
                {
                    hashtable[character] = (int)hashtable[character] + 1;
                }
                else
                {
                    hashtable.Add(character, 1);
                }
                //Console.WriteLine($"character -'{character}'; letters[character]-'{letters[character]}'");
            }

            var str2AsArray = str2.ToCharArray();

            str2AsArray.Print($"'{str2}'- valueToTest.ToCharArray():");
            foreach (var character in str2AsArray)
            {
                if (hashtable.ContainsKey(character))
                {
                    hashtable[character] = (int)hashtable[character] - 1;
                }
                else
                {
                    Console.WriteLine($"character= '{character}' does not exists in Hashtable");
                    return(false);
                }

                //why it is -1 vs 0 condition?
                if ((int)hashtable[character] < 0)
                {
                    Console.WriteLine($"character== {character}, (int)hashtable[character] = {(int)hashtable[character]} : (letters[character] < 0 ) = {(int)hashtable[character] < 0}");
                    return(false);
                }
            }

            Console.WriteLine($" Is '{str1}' and {str2} are permutaion= true");
            Console.WriteLine("===================================================================================");

            return(true);
        }
Esempio n. 24
0
        public override void Run()
        {
            var book          = AssortedMethods.GetLongTextBlob();
            var wordFrequence = GetWordFrequency(book);

            Console.WriteLine("Word\t\t Frequence");
            foreach (var word in wordFrequence.Keys)
            {
                Console.WriteLine($"Word :{word}\t Count:{wordFrequence[word]}");
            }
        }
Esempio n. 25
0
        public override void Run()
        {
            const int numberOfRows    = 10;
            const int numberOfColumns = 15;
            var       matrix1         = AssortedMethods.RandomMatrix(numberOfRows, numberOfColumns, 0, 100);

            AssortedMethods.PrintMatrix(matrix1);
            SetZeros(matrix1);
            Console.WriteLine();
            AssortedMethods.PrintMatrix(matrix1);
        }
        public override void Run()
        {
            string[] array = { "apple", "banana", "carrot", "ele", "duck", "papel", "tarroc", "cudk", "eel", "lee" };
            Console.WriteLine(AssortedMethods.StringArrayToString(array));
            Array.Sort(array, new AnagramComparator());
            Console.WriteLine(AssortedMethods.StringArrayToString(array));

            string[] array2 = { "apple", "banana", "carrot", "ele", "duck", "papel", "tarroc", "cudk", "eel", "lee" };
            Sort(array);
            Console.WriteLine(AssortedMethods.StringArrayToString(array));
        }
Esempio n. 27
0
        public void Run()
        {
            var head = AssortedMethods.RandomLinkedList(10, 0, 10);

            Console.WriteLine(head.PrintForward());

            var deleted = DeleteNode(head.Next.Next.Next.Next); // delete node 4

            Console.WriteLine("deleted? {0}", deleted);
            Console.WriteLine(head.PrintForward());
        }
Esempio n. 28
0
        /// <summary>
        /// clear all left to ith position
        /// </summary>
        /// <param name="number"></param>
        /// <param name="i"></param>
        /// <returns></returns>
        public int ClearBitIthrought0_LeftRemoval(int number, int i)
        {
            int mask = -1 << (i + 1);

            Console.WriteLine($"ClearBitIthrought0:(number({number})={AssortedMethods.ToFullBinarystring(number, 4)}) " +
                              $"& mask({mask})={AssortedMethods.ToFullBinarystring(mask, 4)})={(number & mask)}          " +
                              $"mask= ( -1 << (i + 1))={mask}" +
                              $"mask= (-1 << (i + 1))=-1 [{AssortedMethods.ToFullBinarystring(-1, 4)}] << (i + 1) [{AssortedMethods.ToFullBinarystring(i + 1, 4)}]=[{AssortedMethods.ToFullBinarystring(-1 << (i + 1), 4)}]={mask}" +
                              $"");
            return(number & mask);
        }
        public void Run()
        {
            int[] Arr        = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
            var   head       = AssortedMethods.LinkedListWithValue(8, Arr);
            var   resultNode = ReverseList(head, 3);

            while (resultNode.Next != null)
            {
                Console.WriteLine(resultNode.Data + "->");
                resultNode = resultNode.Next;
            }
        }
Esempio n. 30
0
        public override void Run()
        {
            var root = Q4_02_CreateMinimalBSTfromSortedUniqueArray.Create(1, 2, 3);

            BTreePrinter.Print(root);
            var results = AllSequences(root);

            foreach (var list in results)
            {
                AssortedMethods.PrintList(list);
            }
        }