├── .vscode ├── settings.json └── launch.json ├── .project ├── Language and Collections ├── Tree.cs ├── LinkedListDemo.cs ├── StackDemo.cs ├── QueueDemo.cs ├── SortedSetDemo.cs ├── SortedDictionaryDemo.cs ├── ListDemo.cs ├── SortedListDemo.cs ├── HashSetDemo.cs ├── ArrayDemo.cs ├── DictionaryDemo.cs ├── LoopDemo.cs ├── MinMaxValueTest.cs ├── CountMap.cs └── PriorityQueueDemo.cs ├── String ├── Stringclass.cs ├── TST.cs ├── Trie.cs ├── StringTree.cs └── StringMatching.cs ├── Heap └── PQ.cs ├── AlgorithmsChapters ├── CA │ └── IsPrime.cs ├── DP │ ├── MinStairCost.cs │ ├── DiceThrow.cs │ ├── LargestIncreasingSubseq.cs │ ├── Vacation.cs │ ├── LargestPalindromicSubsequence.cs │ ├── StairUniqueWays.cs │ ├── HouseRobber.cs │ ├── LargestBitonicSubseq.cs │ ├── GridMinCost.cs │ ├── GridUniqueWays.cs │ ├── LargestPalindromicSubstr.cs │ ├── Fibo.cs │ ├── LongestCommonSubseq.cs │ ├── FloydWarshall.cs │ ├── MinCostBinaryTree.cs │ ├── StockBuySell.cs │ ├── EditDist.cs │ ├── ALS.cs │ ├── WildCharMatch.cs │ ├── JobScheduling.cs │ ├── MatrixCM.cs │ ├── Knapsack.cs │ └── OptimalBST.cs ├── BT │ ├── TOH.cs │ ├── NQueens.cs │ ├── SubsetSum.cs │ ├── TSP.cs │ ├── Permutations.cs │ └── GraphColouring.cs ├── Greedy │ ├── ActivitySelection.cs │ ├── Knapsack.cs │ ├── FractionalKnapsack.cs │ ├── MultipleStageGraph.cs │ ├── JobSequencing.cs │ ├── OptimalMergePattern.cs │ └── PriorityQueue.cs └── DAC │ ├── NutsAndBolts.cs │ └── ClosestPair.cs ├── Sorting ├── InsertionSort.cs ├── CountSort.cs ├── ShellSort.cs ├── QuickSort.cs ├── QuickSelect.cs ├── MergeSort1.cs ├── SelectionSort.cs ├── RadixSort.cs ├── BubbleSort.cs ├── MergeSort.cs └── BucketSort.cs ├── Queue ├── QueueUsingStack.cs ├── Stack.cs ├── Queue.cs └── QueueLL.cs ├── Introduction ├── .vscode │ └── settings.json └── Introduction.cs ├── README.md ├── Stack ├── Stack.cs ├── StackLL.cs ├── TwoStack.cs └── Stack2.cs ├── Tree ├── BinaryIndexTree.cs ├── SegmentTree.cs └── RangeMaxST.cs ├── LinkedList └── Polynomial.cs ├── FENWICK └── Program.cs ├── Searching └── BitManipulation.cs └── HashTable ├── HashTableSC.cs ├── HashTableLP.cs └── HashTableExercise.cs /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.formatOnPaste": true, 3 | "editor.formatOnSave": true, 4 | "editor.formatOnType": true, 5 | "editor.formatOnSaveMode": "modifications", 6 | "emmet.includeLanguages": { 7 | "aspnetcorerazor": "html" 8 | } 9 | } -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Problem-Solving-in-Data-Structures-Algorithms-using-CSharp 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Language and Collections/Tree.cs: -------------------------------------------------------------------------------- 1 | public class Tree 2 | { 3 | private class Node 4 | { 5 | internal int value; 6 | internal Node lChild; 7 | internal Node rChild; 8 | // Nested Class Node other fields and methods. 9 | } 10 | 11 | private Node root; 12 | // Outer Class Tree other fields and methods. 13 | } -------------------------------------------------------------------------------- /String/Stringclass.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class Stringclass 4 | { 5 | 6 | public static void Main(string[] args) 7 | { 8 | string str1 = "hello"; 9 | string str2 = "hello"; 10 | string str3 = "Hello"; 11 | Console.WriteLine("str1 equals str2 :" + str1.Equals(str2)); 12 | Console.WriteLine("str1 equals str3 :" + str1.Equals(str3)); 13 | } 14 | } 15 | /* 16 | str1 equals str2 :True 17 | str1 equals str3 :False 18 | */ 19 | -------------------------------------------------------------------------------- /Heap/PQ.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | public class HeapEx 5 | { 6 | public static void Main(string[] args) 7 | { 8 | PriorityQueue queue = new PriorityQueue(); 9 | queue.Enqueue("A", 95); 10 | queue.Enqueue("B", 96); 11 | queue.Enqueue("C", 97); 12 | queue.Enqueue("D", 98); 13 | while (queue.TryDequeue(out string item, out int priority)) 14 | { 15 | Console.WriteLine($"Popped Item : {item}. Priority Was : {priority}"); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /AlgorithmsChapters/CA/IsPrime.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class IsPrime 4 | { 5 | public static bool TestPrime(int n) 6 | { 7 | bool answer = (n > 1) ? true : false; 8 | for (int i = 2; i * i <= n; ++i) 9 | { 10 | if (n % i == 0) 11 | { 12 | answer = false; 13 | break; 14 | } 15 | } 16 | return answer; 17 | } 18 | 19 | // Testing code. 20 | public static void Main(string[] args) 21 | { 22 | Console.WriteLine(IsPrime.TestPrime(7)); 23 | } 24 | } 25 | // True -------------------------------------------------------------------------------- /Language and Collections/LinkedListDemo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | public class LinkedListDemo 4 | { 5 | public static void Main(string[] args) 6 | { 7 | LinkedList ll = new LinkedList(); 8 | ll.AddFirst(1); 9 | ll.AddLast(3); 10 | ll.AddFirst(2); 11 | ll.AddLast(4); 12 | Console.Write("Linked List: "); 13 | foreach (var ele in ll) 14 | Console.Write(ele + " "); 15 | Console.WriteLine(); 16 | ll.RemoveFirst(); 17 | ll.RemoveLast(); 18 | Console.Write("Linked List: "); 19 | foreach (var ele in ll) 20 | Console.Write(ele + " "); 21 | Console.WriteLine(); 22 | } 23 | } 24 | 25 | /* 26 | Linked List: 2 1 3 4 27 | Linked List: 1 3 28 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/DP/MinStairCost.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class MinStairCost 4 | { 5 | public static int MinCost(int[] cost, int n) 6 | { 7 | // base case 8 | if (n == 1) 9 | { 10 | return cost[0]; 11 | } 12 | 13 | int[] dp = new int[n]; 14 | dp[0] = cost[0]; 15 | dp[1] = cost[1]; 16 | 17 | for (int i = 2; i < n; i++) 18 | { 19 | dp[i] = Math.Min(dp[i - 1], dp[i - 2]) + cost[i]; 20 | } 21 | 22 | return Math.Min(dp[n - 2], dp[n - 1]); 23 | } 24 | 25 | // Testing code. 26 | public static void Main(string[] args) 27 | { 28 | int[] a = new int[] {1, 5, 6, 3, 4, 7, 9, 1, 2, 11}; 29 | int n = a.Length; 30 | Console.Write(MinCost(a, n)); 31 | } 32 | } 33 | 34 | /* 35 | 18 36 | */ -------------------------------------------------------------------------------- /Language and Collections/StackDemo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | public class StackDemo 5 | { 6 | public static void Main(string[] args) 7 | { 8 | Stack stack = new Stack(); 9 | stack.Push(1); 10 | stack.Push(2); 11 | stack.Push(3); 12 | Console.Write("Stack : "); 13 | foreach (var ele in stack) 14 | Console.Write(ele + " "); 15 | Console.WriteLine(); 16 | 17 | Console.WriteLine("Stack size : " + stack.Count); 18 | Console.WriteLine("Stack pop : " + stack.Pop()); 19 | Console.WriteLine("Stack top : " + stack.Peek()); 20 | Console.WriteLine("Stack isEmpty : " + (stack.Count == 0)); 21 | } 22 | } 23 | 24 | /* 25 | Stack : 3 2 1 26 | Stack size : 3 27 | Stack pop : 3 28 | Stack top : 2 29 | Stack isEmpty : False 30 | */ -------------------------------------------------------------------------------- /Language and Collections/QueueDemo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | class QueueDemo 5 | { 6 | public static void Main(string[] args) 7 | { 8 | Queue que = new Queue(); 9 | que.Enqueue(1); 10 | que.Enqueue(2); 11 | que.Enqueue(3); 12 | 13 | Console.Write("Queue : "); 14 | foreach (var ele in que) 15 | Console.Write(ele + " "); 16 | Console.WriteLine(); 17 | 18 | Console.WriteLine("Queue size : " + que.Count); 19 | Console.WriteLine("Queue peek : " + que.Peek()); 20 | Console.WriteLine("Queue remove : " + que.Dequeue()); 21 | Console.WriteLine("Queue isEmpty : " + (que.Count == 0)); 22 | } 23 | } 24 | 25 | 26 | /* 27 | Queue : 1 2 3 28 | Queue size : 3 29 | Queue peek : 1 30 | Queue remove : 1 31 | Queue isEmpty : False 32 | */ -------------------------------------------------------------------------------- /Language and Collections/SortedSetDemo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | public class SortedSetDemo 5 | { 6 | public static void Main(string[] args) 7 | { 8 | // Create a tree set. 9 | SortedSet ts = new SortedSet(); 10 | // Add elements to the hash set. 11 | ts.Add("Banana"); 12 | ts.Add("Apple"); 13 | ts.Add("Mango"); 14 | foreach (var ele in ts) 15 | { 16 | Console.Write(ele + " "); 17 | } 18 | Console.WriteLine(); 19 | 20 | Console.WriteLine("Apple present : " + ts.Contains("Apple")); 21 | Console.WriteLine("Grapes present : " + ts.Contains("Grapes")); 22 | ts.Remove("Apple"); 23 | Console.WriteLine("Apple present : " + ts.Contains("Apple")); 24 | } 25 | } 26 | 27 | /* 28 | Apple Banana Mango 29 | Apple present : True 30 | Grapes present : False 31 | Apple present : False 32 | */ -------------------------------------------------------------------------------- /Language and Collections/SortedDictionaryDemo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | public class TreeMapDemo 5 | { 6 | public static void Main(string[] args) 7 | { 8 | // create a tree map. 9 | SortedDictionary tm = new SortedDictionary(); 10 | // Put elements into the map 11 | tm["Apple"] = 40; 12 | tm["Banana"] = 10; 13 | tm["Mango"] = 20; 14 | 15 | Console.WriteLine("Size :: " + tm.Count); 16 | foreach (string key in tm.Keys) 17 | { 18 | Console.WriteLine(key + " cost :" + tm[key]); 19 | } 20 | Console.WriteLine("Apple present ::" + tm.ContainsKey("Apple")); 21 | Console.WriteLine("Grapes present :: " + tm.ContainsKey("Grapes")); 22 | } 23 | } 24 | 25 | /* 26 | Size :: 3 27 | Apple cost :40 28 | Banana cost :10 29 | Mango cost :20 30 | Apple present ::True 31 | Grapes present :: False 32 | */ -------------------------------------------------------------------------------- /Language and Collections/ListDemo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | public class ArrayListDemo 5 | { 6 | public static void Main(string[] args) 7 | { 8 | List ll = new List(); 9 | ll.Add(1); // Add 1 to the end of the list. 10 | ll.Add(2); // Add 2 to the end of the list. 11 | ll.Add(3); // Add 3 to the end of the list. 12 | 13 | Console.Write("Contents of List: "); 14 | foreach (var ele in ll) 15 | Console.Write(ele + " "); 16 | Console.WriteLine(); 17 | 18 | Console.WriteLine("List Size : " + ll.Count); 19 | Console.WriteLine("List IsEmpty : " + (ll.Count == 0)); 20 | ll.RemoveAt(ll.Count - 1); // Last element of list is removed. 21 | ll.Clear(); // lll the elements of list are removed. 22 | Console.WriteLine("List IsEmpty : " + (ll.Count == 0)); 23 | } 24 | } 25 | 26 | /* 27 | Contents of List : 1 2 3 28 | List Size : 3 29 | List IsEmpty : False 30 | List IsEmpty : True 31 | */ 32 | -------------------------------------------------------------------------------- /Sorting/InsertionSort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class InsertionSort 4 | { 5 | private bool Greater(int value1, int value2) 6 | { 7 | return value1 > value2; 8 | } 9 | 10 | public void Sort(int[] arr) 11 | { 12 | int size = arr.Length; 13 | int temp, j; 14 | for (int i = 1; i < size; i++) 15 | { 16 | temp = arr[i]; 17 | for (j = i; j > 0 && Greater(arr[j - 1], temp); j--) 18 | { 19 | arr[j] = arr[j - 1]; 20 | } 21 | arr[j] = temp; 22 | } 23 | } 24 | 25 | // Testing code. 26 | public static void Main(string[] args) 27 | { 28 | int[] array = new int[] {9, 1, 8, 2, 7, 3, 6, 4, 5}; 29 | InsertionSort srt = new InsertionSort(); 30 | srt.Sort(array); 31 | for (int i = 0; i < array.Length; i++) 32 | { 33 | Console.Write(array[i] + " "); 34 | 35 | } 36 | } 37 | } 38 | /* 39 | 1 2 3 4 5 6 7 8 9 40 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/DP/DiceThrow.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class DiceThrow 4 | { 5 | public static int FindWays(int n, int m, int V) 6 | { 7 | int[,] dp = new int[n + 1, V + 1]; 8 | 9 | // Table entries for only one dice. 10 | for (int j = 1; j <= m && j <= V; j++) 11 | { 12 | dp[1, j] = 1; 13 | } 14 | 15 | // i is number of dice, j is Value, k value of dice. 16 | for (int i = 2; i <= n; i++) 17 | { 18 | for (int j = 1; j <= V; j++) 19 | { 20 | for (int k = 1; k <= j && k <= m; k++) 21 | { 22 | dp[i, j] += dp[i - 1, j - k]; 23 | } 24 | } 25 | } 26 | return dp[n, V]; 27 | } 28 | 29 | // Testing code. 30 | public static void Main(string[] args) 31 | { 32 | for (int i = 1; i <= 6; i++) 33 | { 34 | Console.Write(FindWays(i, 6, 6) + " "); 35 | } 36 | } 37 | } 38 | 39 | /* 40 | 1 5 10 10 5 1 41 | */ -------------------------------------------------------------------------------- /Language and Collections/SortedListDemo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | public class SortedListDemo 5 | { 6 | public static void Main(string[] args) 7 | { 8 | // Create a Sorted List. 9 | SortedList tm = new SortedList(); 10 | 11 | // Put elements into Sorted List 12 | tm["Apple"] = 40; 13 | tm["Mango"] = 20; 14 | tm["Banana"] = 10; 15 | 16 | Console.WriteLine("Size :: " + tm.Count); 17 | foreach (string key in tm.Keys) 18 | { 19 | Console.WriteLine(key + " cost :" + tm[key]); 20 | } 21 | 22 | Console.WriteLine("Apple present :: " + tm.ContainsKey("Apple")); 23 | Console.WriteLine("Grapes present :: " + tm.ContainsKey("Grapes")); 24 | 25 | tm.Remove("Apple"); 26 | Console.WriteLine("Apple present :: " + tm.ContainsKey("Apple")); 27 | } 28 | } 29 | /* 30 | Size :: 3 31 | Apple cost :40 32 | Banana cost :10 33 | Mango cost :20 34 | Apple present :: True 35 | Grapes present :: False 36 | Apple present :: False 37 | */ 38 | -------------------------------------------------------------------------------- /Sorting/CountSort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class CountSort 4 | { 5 | public void Sort(int[] arr, int lowerRange, int upperRange) 6 | { 7 | int i, j; 8 | int size = arr.Length; 9 | int range = upperRange - lowerRange; 10 | int[] count = new int[range]; 11 | 12 | for (i = 0; i < size; i++) 13 | { 14 | count[arr[i] - lowerRange]++; 15 | } 16 | 17 | j = 0; 18 | for (i = 0; i < range; i++) 19 | { 20 | for (; count[i] > 0; (count[i])--) 21 | { 22 | arr[j++] = i + lowerRange; 23 | } 24 | } 25 | } 26 | 27 | // Testing code. 28 | public static void Main(string[] args) 29 | { 30 | int[] array = new int[] {23, 24, 22, 21, 26, 25, 27, 28, 21, 21}; 31 | CountSort b = new CountSort(); 32 | b.Sort(array, 20, 30); 33 | for (int i = 0; i < array.Length; i++) 34 | { 35 | Console.Write(array[i] + " "); 36 | } 37 | } 38 | } 39 | 40 | /* 41 | 21 21 21 22 23 24 25 26 27 28 42 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/BT/TOH.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | // Towers Of Hanoi problem. 4 | public class TOH 5 | { 6 | private static void TOHUtil(int num, char from, char to, char temp) 7 | { 8 | if (num < 1) 9 | { 10 | return; 11 | } 12 | 13 | TOHUtil(num - 1, from, temp, to); 14 | Console.WriteLine("Move disk " + num + " from peg " + from + " to peg " + to); 15 | TOHUtil(num - 1, temp, to, from); 16 | } 17 | 18 | public static void TOHSteps(int num) 19 | { 20 | Console.WriteLine("Moves involved in the Tower of Hanoi are :"); 21 | TOHUtil(num, 'A', 'C', 'B'); 22 | } 23 | 24 | // Testing code. 25 | public static void Main(string[] args) 26 | { 27 | TOH.TOHSteps(3); 28 | } 29 | } 30 | /* 31 | Moves involved in the Tower of Hanoi are : 32 | Move disk 1 from peg A to peg C 33 | Move disk 2 from peg A to peg B 34 | Move disk 1 from peg C to peg B 35 | Move disk 3 from peg A to peg C 36 | Move disk 1 from peg B to peg A 37 | Move disk 2 from peg B to peg C 38 | Move disk 1 from peg A to peg C 39 | */ -------------------------------------------------------------------------------- /Language and Collections/HashSetDemo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | public class HashSetDemo 5 | { 6 | public static void Main(string[] args) 7 | { 8 | // Create a hash set. 9 | HashSet hs = new HashSet(); 10 | // Add elements to the hash set. 11 | hs.Add("Banana"); 12 | hs.Add("Apple"); 13 | hs.Add("Mango"); 14 | foreach (var ele in hs) 15 | { 16 | Console.Write(ele + " "); 17 | } 18 | Console.WriteLine(); 19 | 20 | Console.WriteLine("Apple present : " + hs.Contains("Apple")); 21 | Console.WriteLine("Grapes present : " + hs.Contains("Grapes")); 22 | hs.Remove("Apple"); 23 | Console.WriteLine("Apple present : " + hs.Contains("Apple")); 24 | foreach (var ele in hs) 25 | { 26 | Console.Write(ele + " "); 27 | } 28 | Console.WriteLine(); 29 | } 30 | } 31 | 32 | /* 33 | Banana Apple Mango 34 | Apple present : True 35 | Grapes present : False 36 | Apple present : False 37 | Banana Mango 38 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/DP/LargestIncreasingSubseq.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class LargestIncreasingSubseq 4 | { 5 | public static int LIS(int[] arr) 6 | { 7 | int n = arr.Length; 8 | int[] lis = new int[n]; 9 | int max = 0; 10 | 11 | // Populating LIS values in bottom up manner. 12 | for (int i = 0; i < n; i++) 13 | { 14 | lis[i] = 1; // Initialize LIS values for all indexes as 1. 15 | for (int j = 0; j < i; j++) 16 | { 17 | if (arr[j] < arr[i] && lis[i] < lis[j] + 1) 18 | { 19 | lis[i] = lis[j] + 1; 20 | } 21 | } 22 | if (max < lis[i]) // Max LIS values. 23 | { 24 | max = lis[i]; 25 | } 26 | } 27 | return max; 28 | } 29 | 30 | // Testing code. 31 | public static void Main(string[] args) 32 | { 33 | int[] arr = new int[] { 10, 12, 9, 23, 25, 55, 49, 70 }; 34 | Console.WriteLine("Length of LIS is " + LIS(arr)); 35 | } 36 | } 37 | 38 | // Length of lis is 6 39 | -------------------------------------------------------------------------------- /Queue/QueueUsingStack.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | public class QueueUsingStack 5 | { 6 | 7 | private Stack stk1; 8 | private Stack stk2; 9 | 10 | public QueueUsingStack() 11 | { 12 | stk1 = new Stack(); 13 | stk2 = new Stack(); 14 | } 15 | 16 | public void Add(int value) 17 | { 18 | stk1.Push(value); 19 | } 20 | 21 | public int Remove() 22 | { 23 | int value; 24 | if (stk2.Count > 0) 25 | { 26 | return stk2.Pop(); 27 | } 28 | 29 | while (stk1.Count > 0) 30 | { 31 | value = stk1.Pop(); 32 | stk2.Push(value); 33 | } 34 | return stk2.Pop(); 35 | } 36 | 37 | // Testing code. 38 | public static void Main(string[] args) 39 | { 40 | QueueUsingStack que = new QueueUsingStack(); 41 | que.Add(1); 42 | que.Add(2); 43 | que.Add(3); 44 | Console.WriteLine("Queue remove : " + que.Remove()); 45 | Console.WriteLine("Queue remove : " + que.Remove()); 46 | } 47 | } 48 | 49 | /* 50 | 1 51 | 2 52 | */ -------------------------------------------------------------------------------- /Language and Collections/ArrayDemo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class ArrayDemo 4 | { 5 | public static void oneD() 6 | { 7 | int[] arr = new int[10]; 8 | for (int i = 0; i < 10; i++) 9 | { 10 | arr[i] = i; 11 | } 12 | for (int i = 0; i < 10; i++) 13 | { 14 | Console.Write(arr[i] + " "); 15 | } 16 | Console.WriteLine(); 17 | } 18 | 19 | private static void twoD() 20 | { 21 | int[,] arr = new int[4, 4]; 22 | 23 | for (int i = 0; i < 4; i++) 24 | { 25 | for (int j = 0; j < 4; j++) 26 | { 27 | arr[i, j] = i + j; 28 | } 29 | } 30 | 31 | for (int i = 0; i < 4; i++) 32 | { 33 | for (int j = 0; j < 4; j++) 34 | { 35 | Console.Write(arr[i, j]); 36 | } 37 | Console.WriteLine(" "); 38 | } 39 | } 40 | 41 | // Testing code. 42 | public static void Main(string[] args) 43 | { 44 | oneD(); 45 | twoD(); 46 | } 47 | } 48 | 49 | /* 50 | 0 1 2 3 4 5 6 7 8 9 51 | 52 | 0123 53 | 1234 54 | 2345 55 | 3456 56 | */ -------------------------------------------------------------------------------- /Language and Collections/DictionaryDemo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | /* 5 | A Dictionary is an object that stores associations between keys and values, or key/value pairs. 6 | Both keys and values are objects. The keys must be unique, but the values may be duplicated. 7 | */ 8 | 9 | public class DictionaryDemo 10 | { 11 | // Testing code. 12 | public static void Main(string[] args) 13 | { 14 | // Create a dictionary. 15 | Dictionary hm = new Dictionary(); 16 | 17 | // Add elements into the dictionary. 18 | hm["Apple"] = 40; 19 | hm["Banana"] = 10; 20 | hm["Mango"] = 20; 21 | 22 | Console.WriteLine("Dictionary Size :: " + hm.Count); 23 | foreach (string key in hm.Keys) 24 | { 25 | Console.WriteLine(key + " cost :" + hm[key]); 26 | } 27 | 28 | Console.WriteLine("Apple present ::" + hm.ContainsKey("Apple")); 29 | Console.WriteLine("Grapes present :: " + hm.ContainsKey("Grapes")); 30 | } 31 | } 32 | 33 | /* 34 | Dictionary Size :: 3 35 | Apple cost :40 36 | Banana cost :10 37 | Mango cost :20 38 | Apple present ::True 39 | Grapes present :: False 40 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/DP/Vacation.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class Vacation 4 | { 5 | // days are must travel days, costs are cost of tickets. 6 | public static int MinCostTravel(int[] days, int[] costs) 7 | { 8 | int n = days.Length; 9 | int max = days[n - 1]; 10 | int[] dp = new int[max + 1]; 11 | 12 | int j = 0; 13 | for (int i = 1; i <= max; i++) 14 | { 15 | if (days[j] == i) // That days is definitely travelled. 16 | { 17 | j++; 18 | dp[i] = dp[i - 1] + costs[0]; 19 | dp[i] = Math.Min(dp[i], dp[Math.Max(0, i - 7)] + costs[1]); 20 | dp[i] = Math.Min(dp[i], dp[Math.Max(0, i - 30)] + costs[2]); 21 | } 22 | else 23 | { 24 | dp[i] = dp[i - 1]; // day may be ignored. 25 | } 26 | } 27 | return dp[max]; 28 | } 29 | 30 | // Testing code. 31 | public static void Main(string[] args) 32 | { 33 | int[] days = new int[] { 1, 3, 5, 7, 12, 20, 30 }; 34 | int[] costs = new int[] { 2, 7, 20 }; 35 | Console.WriteLine("Min cost is:" + MinCostTravel(days, costs)); 36 | } 37 | } 38 | /* 39 | Min cost is:13 40 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/DP/LargestPalindromicSubsequence.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | // Palindromic Subsequence 4 | public class LargestPalindromicSubsequence 5 | { 6 | public static int PalindromicSubsequence(string str) 7 | { 8 | int n = str.Length; 9 | int[,] dp = new int[n, n]; 10 | 11 | for (int i = 0; i < n; i++) // each char is itself palindromic with length 1 12 | { 13 | dp[i, i] = 1; 14 | } 15 | 16 | for (int l = 1; l < n; l++) 17 | { 18 | for (int i = 0, j = l; j < n; i++, j++) 19 | { 20 | if (str[i] == str[j]) 21 | { 22 | dp[i, j] = dp[i + 1, j - 1] + 2; 23 | } 24 | else 25 | { 26 | dp[i, j] = Math.Max(dp[i + 1, j], dp[i, j - 1]); 27 | } 28 | } 29 | } 30 | return dp[0, n - 1]; 31 | } 32 | 33 | // Testing code. 34 | public static void Main(string[] args) 35 | { 36 | string str = "ABCAUCBCxxCBA"; 37 | Console.WriteLine("Max Palindromic Subsequence length: " + PalindromicSubsequence(str)); 38 | 39 | } 40 | } 41 | 42 | /* 43 | Max Palindromic Subsequence length: 9 44 | */ 45 | -------------------------------------------------------------------------------- /AlgorithmsChapters/DP/StairUniqueWays.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class StairUniqueWays 4 | { 5 | public static int UniqueWaysBU(int n) 6 | { 7 | if (n <= 2) 8 | { 9 | return n; 10 | } 11 | 12 | int first = 1, second = 2; 13 | int temp = 0; 14 | 15 | for (int i = 3; i <= n; i++) 16 | { 17 | temp = first + second; 18 | first = second; 19 | second = temp; 20 | } 21 | return temp; 22 | } 23 | 24 | public static int UniqueWaysBU2(int n) 25 | { 26 | if (n < 2) 27 | { 28 | return n; 29 | } 30 | 31 | int[] ways = new int[n]; 32 | ways[0] = 1; 33 | ways[1] = 2; 34 | 35 | for (int i = 2; i < n; i++) 36 | { 37 | ways[i] = ways[i - 1] + ways[i - 2]; 38 | } 39 | 40 | return ways[n - 1]; 41 | } 42 | 43 | // Testing code. 44 | public static void Main(string[] args) 45 | { 46 | Console.WriteLine("Unique way to reach top:: " + UniqueWaysBU(4)); 47 | Console.WriteLine("Unique way to reach top:: " + UniqueWaysBU2(4)); 48 | } 49 | } 50 | /* 51 | Unique way to reach top:: 5 52 | Unique way to reach top:: 5 53 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/DP/HouseRobber.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class HouseRobber 4 | { 5 | public static int MaxRobbery(int[] house) 6 | { 7 | int n = house.Length; 8 | int[] dp = new int[n]; 9 | dp[0] = house[0]; 10 | dp[1] = house[1]; 11 | dp[2] = dp[0] + house[2]; 12 | for (int i = 3; i < n; i++) 13 | { 14 | dp[i] = Math.Max(dp[i - 2], dp[i - 3]) + house[i]; 15 | } 16 | return Math.Max(dp[n - 1], dp[n - 2]); 17 | } 18 | 19 | public static int MaxRobbery2(int[] house) 20 | { 21 | int n = house.Length; 22 | int[,] dp = new int[n, 2]; 23 | 24 | dp[0, 1] = house[0]; 25 | dp[0, 0] = 0; 26 | 27 | for (int i = 1; i < n; ++i) 28 | { 29 | dp[i, 1] = Math.Max(dp[i - 1, 0] + house[i], dp[i - 1, 1]); 30 | dp[i, 0] = dp[i - 1, 1]; 31 | } 32 | return Math.Max(dp[n - 1, 1], dp[n - 1, 0]); 33 | } 34 | 35 | // Testing code. 36 | public static void Main(string[] args) 37 | { 38 | int[] arr = new int[] { 10, 12, 9, 23, 25, 55, 49, 70 }; 39 | Console.WriteLine("Total cash: " + MaxRobbery(arr)); 40 | Console.WriteLine("Total cash: " + MaxRobbery2(arr)); 41 | } 42 | } 43 | 44 | /* 45 | Total cash: 160 46 | Total cash: 160 47 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/BT/NQueens.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class NQueens 4 | { 5 | public static void Print(int[] Q, int n) 6 | { 7 | for (int i = 0; i < n; i++) 8 | { 9 | Console.Write(" " + Q[i]); 10 | } 11 | Console.WriteLine(" "); 12 | } 13 | 14 | public static bool Feasible(int[] Q, int k) 15 | { 16 | for (int i = 0; i < k; i++) 17 | { 18 | if (Q[k] == Q[i] || Math.Abs(Q[i] - Q[k]) == Math.Abs(i - k)) 19 | { 20 | return false; 21 | } 22 | } 23 | return true; 24 | } 25 | 26 | public static void NQueensPattern(int[] Q, int k, int n) 27 | { 28 | if (k == n) 29 | { 30 | Print(Q, n); 31 | return; 32 | } 33 | for (int i = 0; i < n; i++) 34 | { 35 | Q[k] = i; 36 | if (Feasible(Q, k)) 37 | { 38 | NQueensPattern(Q, k + 1, n); 39 | } 40 | } 41 | } 42 | 43 | // Testing code. 44 | public static void Main(string[] args) 45 | { 46 | int[] Q = new int[8]; 47 | NQueensPattern(Q, 0, 8); 48 | } 49 | } 50 | 51 | /* 52 | 0 4 7 5 2 6 1 3 53 | 0 5 7 2 6 3 1 4 54 | ...... 55 | 7 2 0 5 1 4 6 3 56 | 7 3 0 2 5 1 6 4 57 | */ -------------------------------------------------------------------------------- /Language and Collections/LoopDemo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class ForDemo 4 | { 5 | 6 | internal const double PI = 3.141592653589793; 7 | 8 | public static void main1() 9 | { 10 | int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 11 | int sum = 0; 12 | foreach (int n in numbers) 13 | { 14 | sum += n; 15 | } 16 | 17 | Console.WriteLine("Sum is :: " + sum); 18 | } 19 | 20 | public static void main2() 21 | { 22 | int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 23 | int sum = 0; 24 | for (int i = 0; i < numbers.Length; i++) 25 | { 26 | sum += numbers[i]; 27 | } 28 | 29 | Console.WriteLine("Sum is :: " + sum); 30 | } 31 | 32 | public static void main3() 33 | { 34 | int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 35 | int sum = 0; 36 | int i = 0; 37 | while (i < numbers.Length) 38 | { 39 | sum += numbers[i]; 40 | i++; 41 | } 42 | Console.WriteLine("Sum is :: " + sum); 43 | } 44 | 45 | public static void Main(string[] args) 46 | { 47 | main1(); 48 | main2(); 49 | main3(); 50 | } 51 | } 52 | 53 | /* 54 | Sum is :: 55 55 | Sum is :: 55 56 | Sum is :: 55 57 | */ -------------------------------------------------------------------------------- /Introduction/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "array": "cpp", 4 | "atomic": "cpp", 5 | "bit": "cpp", 6 | "*.tcc": "cpp", 7 | "cctype": "cpp", 8 | "clocale": "cpp", 9 | "cmath": "cpp", 10 | "cstdarg": "cpp", 11 | "cstddef": "cpp", 12 | "cstdint": "cpp", 13 | "cstdio": "cpp", 14 | "cstdlib": "cpp", 15 | "cwchar": "cpp", 16 | "cwctype": "cpp", 17 | "deque": "cpp", 18 | "unordered_map": "cpp", 19 | "vector": "cpp", 20 | "exception": "cpp", 21 | "algorithm": "cpp", 22 | "functional": "cpp", 23 | "iterator": "cpp", 24 | "memory": "cpp", 25 | "memory_resource": "cpp", 26 | "numeric": "cpp", 27 | "optional": "cpp", 28 | "random": "cpp", 29 | "string": "cpp", 30 | "string_view": "cpp", 31 | "system_error": "cpp", 32 | "tuple": "cpp", 33 | "type_traits": "cpp", 34 | "utility": "cpp", 35 | "fstream": "cpp", 36 | "initializer_list": "cpp", 37 | "iosfwd": "cpp", 38 | "iostream": "cpp", 39 | "istream": "cpp", 40 | "limits": "cpp", 41 | "new": "cpp", 42 | "ostream": "cpp", 43 | "sstream": "cpp", 44 | "stdexcept": "cpp", 45 | "streambuf": "cpp", 46 | "typeinfo": "cpp" 47 | } 48 | } -------------------------------------------------------------------------------- /Sorting/ShellSort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class ShellSort 4 | { 5 | private bool Greater(int value1, int value2) 6 | { 7 | return value1 > value2; 8 | } 9 | 10 | public void Sort(int[] arr) 11 | { 12 | int n = arr.Length; 13 | 14 | // Gap starts with n/2 and half in each iteration. 15 | for (int gap = n / 2; gap > 0; gap /= 2) 16 | { 17 | // Do a gapped insertion Sort. 18 | for (int i = gap; i < n; i += 1) 19 | { 20 | int curr = arr[i]; 21 | 22 | // Shift elements of already Sorted list 23 | // to find right position for curr value. 24 | int j; 25 | for (j = i; j >= gap && Greater(arr[j - gap], curr); j -= gap) 26 | { 27 | arr[j] = arr[j - gap]; 28 | } 29 | 30 | // Put current value in its correct location 31 | arr[j] = curr; 32 | } 33 | } 34 | } 35 | 36 | // Testing code. 37 | public static void Main(string[] args) 38 | { 39 | int[] array = new int[] {36, 32, 11, 6, 19, 31, 17, 3}; 40 | 41 | ShellSort b = new ShellSort(); 42 | b.Sort(array); 43 | for (int i = 0; i < array.Length; i++) 44 | { 45 | Console.Write(array[i] + " "); 46 | } 47 | } 48 | } 49 | 50 | /* 51 | 3 6 11 17 19 31 32 36 52 | */ -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Problem-Solving-in-Data-Structures-Algorithms-using-C# 2 | 3 | This is the code repository of book **Problem Solving in Data Structures & Algorithms using C#**. 4 | 5 | ![alt text](https://m.media-amazon.com/images/P/B0BL3Y7HB5.jpg) 6 | 7 | 8 | **About The Book** 9 | - This textbook provides in depth coverage of various Data Structures and Algorithms. 10 | - Concepts are discussed in easy to understand manner. 11 | - Large number of diagrams are provided to grasp concepts easily. 12 | - Time and Space complexities of various algorithms are discussed. 13 | - Helpful for interviews preparation and competitive coding. 14 | - Large number of interview questions are solved. 15 | - C# solutions are provided with input and output. 16 | - Guide you through how to solve new problems in programming interview of various software companies. 17 | 18 | 19 | **Table of Contents** 20 | - Chapter 0: How to use this book. 21 | - Chapter 1: Algorithms Analysis 22 | - Chapter 2: Approach to solve algorithm design problems 23 | - Chapter 3: Abstract Data Type & C# Collections 24 | - Chapter 4: Searching 25 | - Chapter 5: Sorting 26 | - Chapter 6: Linked List 27 | - Chapter 7: Stack 28 | - Chapter 8: Queue 29 | - Chapter 9: Tree 30 | - Chapter 10: Priority Queue 31 | - Chapter 11: Hash-Table 32 | - Chapter 12: Graphs 33 | - Chapter 13: String Algorithms 34 | - Chapter 14: Algorithm Design Techniques 35 | - Chapter 15: Brute Force Algorithm 36 | - Chapter 16: Greedy Algorithm 37 | - Chapter 17: Divide & Conquer 38 | - Chapter 18: Dynamic Programming 39 | - Chapter 19: Backtracking 40 | - Chapter 20: Complexity Theory 41 | 42 | -------------------------------------------------------------------------------- /Language and Collections/MinMaxValueTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class MinMaxValueTest 4 | { 5 | public static void Main(string[] args) 6 | { 7 | 8 | sbyte maxByte = sbyte.MaxValue; 9 | sbyte minByte = sbyte.MinValue; 10 | 11 | short maxShort = short.MaxValue; 12 | short minShort = short.MinValue; 13 | 14 | int maxInteger = int.MaxValue; 15 | int minInteger = int.MinValue; 16 | 17 | long maxLong = long.MaxValue; 18 | long minLong = long.MinValue; 19 | 20 | float maxFloat = float.MaxValue; 21 | float minFloat = float.Epsilon; 22 | 23 | double maxDouble = double.MaxValue; 24 | double minDouble = double.Epsilon; 25 | 26 | Console.WriteLine("Range of byte :: " + minByte + " to " + maxByte + "."); 27 | Console.WriteLine("Range of short :: " + minShort + " to " + maxShort + "."); 28 | Console.WriteLine("Range of integer :: " + minInteger + " to " + maxInteger + "."); 29 | Console.WriteLine("Range of long :: " + minLong + " to " + maxLong + "."); 30 | Console.WriteLine("Range of float :: " + minFloat + " to " + maxFloat + "."); 31 | Console.WriteLine("Range of double :: " + minDouble + " to " + maxDouble + "."); 32 | } 33 | } 34 | 35 | /* 36 | Range of byte :: -128 to 127. 37 | Range of short :: -32768 to 32767. 38 | Range of integer :: -2147483648 to 2147483647. 39 | Range of long :: -9223372036854775808 to 9223372036854775807. 40 | Range of float :: 1.401298E-45 to 3.402823E+38. 41 | Range of double :: 4.94065645841247E-324 to 1.79769313486232E+308. 42 | */ -------------------------------------------------------------------------------- /Language and Collections/CountMap.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | public class CountMap 5 | { 6 | internal Dictionary hm = new Dictionary(); 7 | 8 | public void Add(T key) 9 | { 10 | if (hm.ContainsKey(key)) 11 | { 12 | hm[key] = hm[key] + 1; 13 | } 14 | else 15 | { 16 | hm[key] = 1; 17 | } 18 | } 19 | 20 | public void Remove(T key) 21 | { 22 | if (hm.ContainsKey(key)) 23 | { 24 | if (hm[key] == 1) 25 | { 26 | hm.Remove(key); 27 | } 28 | else 29 | { 30 | hm[key] = hm[key] - 1; 31 | } 32 | } 33 | } 34 | 35 | public int Get(T key) 36 | { 37 | if (hm.ContainsKey(key)) 38 | { 39 | return hm[key]; 40 | } 41 | return 0; 42 | } 43 | 44 | public bool ContainsKey(T key) 45 | { 46 | return hm.ContainsKey(key); 47 | } 48 | 49 | public int size() 50 | { 51 | return hm.Count; 52 | } 53 | } 54 | class countMapDemo 55 | { 56 | // Testing code. 57 | public static void Main(string[] args) 58 | { 59 | CountMap cm = new CountMap(); 60 | cm.Add(2); 61 | cm.Add(2); 62 | Console.WriteLine("count is : " + cm.Get(2)); 63 | cm.Remove(2); 64 | Console.WriteLine("count is : " + cm.Get(2)); 65 | cm.Remove(2); 66 | Console.WriteLine("count is : " + cm.Get(2)); 67 | } 68 | } 69 | 70 | /* 71 | count is : 2 72 | count is : 1 73 | count is : 0 74 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/DP/LargestBitonicSubseq.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class LargestBitonicSubseq 4 | { 5 | public static int LBS(int[] arr) 6 | { 7 | int n = arr.Length; 8 | int[] lis = new int[n]; 9 | Array.Fill(lis, 1); // Initialize LIS values for all indexes as 1. 10 | int[] lds = new int[n]; 11 | Array.Fill(lds, 1); // Initialize LDS values for all indexes as 1. 12 | int max = 0; 13 | 14 | // Populating LIS values in bottom up manner. 15 | for (int i = 0; i < n; i++) 16 | { 17 | for (int j = 0; j < i; j++) 18 | { 19 | if (arr[j] < arr[i] && lis[i] < lis[j] + 1) 20 | { 21 | lis[i] = lis[j] + 1; 22 | } 23 | } 24 | } 25 | 26 | // Populating LDS values in bottom up manner. 27 | for (int i = n - 1; i > 0; i--) 28 | { 29 | for (int j = n - 1; j > i; j--) 30 | { 31 | if (arr[j] < arr[i] && lds[i] < lds[j] + 1) 32 | { 33 | lds[i] = lds[j] + 1; 34 | } 35 | } 36 | } 37 | for (int i = 0; i < n; i++) 38 | { 39 | max = Math.Max(max, lis[i] + lds[i] - 1); 40 | } 41 | 42 | return max; 43 | } 44 | 45 | // Testing code. 46 | public static void Main(string[] args) 47 | { 48 | int[] arr = new int[] { 1, 6, 3, 11, 1, 9, 5, 12, 3, 14, 6, 17, 3, 19, 2, 19 }; 49 | Console.WriteLine("Length of LBS is " + LBS(arr)); 50 | } 51 | } 52 | /* 53 | Length of LBS is 8 54 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/BT/SubsetSum.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class SubsetSum 4 | { 5 | private static void PrintSubset(bool[] flags, int[] arr, int size) 6 | { 7 | for (int i = 0; i < size; i++) 8 | { 9 | if (flags[i]) 10 | { 11 | Console.Write(arr[i] + " "); 12 | } 13 | } 14 | Console.WriteLine(); 15 | } 16 | 17 | public static void FindSubsetSum(int[] arr, int n, int target) 18 | { 19 | bool[] flags = new bool[n]; 20 | FindSubsetSum(arr, n, flags, 0, 0, target); 21 | } 22 | 23 | private static void FindSubsetSum(int[] arr, int n, bool[] flags, int sum, int curr, int target) 24 | { 25 | if (target == sum) 26 | { 27 | PrintSubset(flags, arr, n); // Solution found. 28 | return; 29 | } 30 | 31 | // constraint check 32 | if (curr >= n || sum > target) 33 | { 34 | // Backtracking. 35 | return; 36 | } 37 | 38 | // Current element included. 39 | flags[curr] = true; 40 | FindSubsetSum(arr, n, flags, sum + arr[curr], curr + 1, target); 41 | // Current element excluded. 42 | flags[curr] = false; 43 | FindSubsetSum(arr, n, flags, sum, curr + 1, target); 44 | } 45 | 46 | // Testing code. 47 | public static void Main(string[] args) 48 | { 49 | int[] arr = new int[] { 15, 22, 14, 26, 32, 9, 16, 8 }; 50 | int target = 53; 51 | int n = arr.Length; 52 | SubsetSum.FindSubsetSum(arr, n, target); 53 | } 54 | } 55 | 56 | /* 57 | 15 22 16 58 | 15 14 16 8 59 | 22 14 9 8 60 | */ -------------------------------------------------------------------------------- /Sorting/QuickSort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class QuickSort 4 | { 5 | private void Sort(int[] arr, int lower, int upper) 6 | { 7 | if (upper <= lower) 8 | { 9 | return; 10 | } 11 | int pivot = arr[lower]; 12 | int start = lower; 13 | int stop = upper; 14 | 15 | while (lower < upper) 16 | { 17 | while (arr[lower] <= pivot && lower < upper) 18 | { 19 | lower++; 20 | } 21 | while (arr[upper] > pivot && lower <= upper) 22 | { 23 | upper--; 24 | } 25 | if (lower < upper) 26 | { 27 | Swap(arr, upper, lower); 28 | } 29 | } 30 | Swap(arr, upper, start); // upper is the pivot position 31 | Sort(arr, start, upper - 1); // pivot -1 is the upper for left sub array. 32 | Sort(arr, upper + 1, stop); // pivot + 1 is the lower for right sub array 33 | } 34 | 35 | public void Sort(int[] arr) 36 | { 37 | int size = arr.Length; 38 | Sort(arr, 0, size - 1); 39 | } 40 | 41 | private void Swap(int[] arr, int first, int second) 42 | { 43 | int temp = arr[first]; 44 | arr[first] = arr[second]; 45 | arr[second] = temp; 46 | } 47 | 48 | // Testing code. 49 | public static void Main(string[] args) 50 | { 51 | int[] array = new int[] {3, 4, 2, 1, 6, 5, 7, 8, 10, 9}; 52 | QuickSort srt = new QuickSort(); 53 | srt.Sort(array); 54 | for (int i = 0; i < array.Length; i++) 55 | { 56 | Console.Write(array[i] + " "); 57 | } 58 | } 59 | } 60 | // 1 2 3 4 5 6 7 8 9 10 -------------------------------------------------------------------------------- /AlgorithmsChapters/Greedy/ActivitySelection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class ActivitySelection 4 | { 5 | internal class Activity : IComparable 6 | { 7 | internal int start, stop; 8 | 9 | internal Activity(int s, int f) 10 | { 11 | start = s; 12 | stop = f; 13 | } 14 | 15 | public int CompareTo(Activity s2) 16 | { 17 | return this.stop - s2.stop; 18 | } 19 | } 20 | 21 | public void MaxActivities(int[] s, int[] f, int n) 22 | { 23 | Activity[] act = new Activity[n]; 24 | int i; 25 | for (i = 0; i < n; i++) 26 | { 27 | act[i] = new Activity(s[i], f[i]); 28 | } 29 | Array.Sort(act); // sort according to finish time. 30 | 31 | i = 0; // The first activity at index 0 is always gets selected. 32 | Console.Write("Activities are : (" + act[i].start + "," + act[i].stop + ")"); 33 | 34 | for (int j = 1; j < n; j++) 35 | { 36 | // Find next activity whose start time is greater than or equal 37 | // to the finish time of previous activity. 38 | if (act[j].start >= act[i].stop) 39 | { 40 | Console.Write(", (" + act[j].start + "," + act[j].stop + ")"); 41 | i = j; 42 | } 43 | } 44 | } 45 | 46 | // Testing code. 47 | public static void Main(string[] args) 48 | { 49 | int[] s = new int[] { 1, 5, 0, 3, 5, 6, 8 }; 50 | int[] f = new int[] { 2, 6, 5, 4, 9, 7, 9 }; 51 | int n = s.Length; 52 | ActivitySelection act = new ActivitySelection(); 53 | act.MaxActivities(s, f, n); 54 | } 55 | } 56 | 57 | /* 58 | Activities are : (1,2), (3,4), (5,6), (6,7), (8,9) 59 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/DP/GridMinCost.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class GridMinCost 4 | { 5 | private static int Min(int x, int y, int z) 6 | { 7 | x = Math.Min(x, y); 8 | return Math.Min(x, z); 9 | } 10 | 11 | public static int MinCost(int[,] cost, int m, int n) 12 | { 13 | if (m == 0 || n == 0) 14 | { 15 | return 99999; 16 | } 17 | 18 | if (m == 1 && n == 1) 19 | { 20 | return cost[0, 0]; 21 | } 22 | 23 | return cost[m - 1, n - 1] + Min(MinCost(cost, m - 1, n - 1), MinCost(cost, m - 1, n), MinCost(cost, m, n - 1)); 24 | } 25 | 26 | public static int MinCostBU(int[,] cost, int m, int n) 27 | { 28 | int[,] tc = new int[m, n]; 29 | tc[0, 0] = cost[0, 0]; 30 | 31 | // Initialize first column. 32 | for (int i = 1; i < m; i++) 33 | { 34 | tc[i, 0] = tc[i - 1, 0] + cost[i, 0]; 35 | } 36 | // Initialize first row. 37 | for (int j = 1; j < n; j++) 38 | { 39 | tc[0, j] = tc[0, j - 1] + cost[0, j]; 40 | } 41 | 42 | for (int i = 1; i < m; i++) 43 | { 44 | for (int j = 1; j < n; j++) 45 | { 46 | tc[i, j] = cost[i, j] + Min(tc[i - 1, j - 1], tc[i - 1, j], tc[i, j - 1]); 47 | } 48 | } 49 | return tc[m - 1, n - 1]; 50 | } 51 | 52 | // Testing code. 53 | public static void Main(string[] args) 54 | { 55 | int[,] cost = new int[,] { { 1, 3, 4 }, { 4, 7, 5 }, { 1, 5, 3 } }; 56 | Console.WriteLine("GridMinCost : " + MinCost(cost, 3, 3)); 57 | Console.WriteLine("GridMinCost : " + MinCostBU(cost, 3, 3)); 58 | } 59 | } 60 | 61 | /* 62 | GridMinCost : 11 63 | GridMinCost : 11 64 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/DP/GridUniqueWays.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class GridUniqueWays 4 | { 5 | public static int UniqueWays(int m, int n) 6 | { 7 | int[,] dp = new int[m, n]; 8 | dp[0, 0] = 1; 9 | 10 | // Initialize first column. 11 | for (int i = 1; i < m; i++) 12 | { 13 | dp[i, 0] = dp[i - 1, 0]; 14 | } 15 | // Initialize first row. 16 | for (int j = 1; j < n; j++) 17 | { 18 | dp[0, j] = dp[0, j - 1]; 19 | } 20 | 21 | for (int i = 1; i < m; i++) 22 | { 23 | for (int j = 1; j < n; j++) 24 | { 25 | dp[i, j] = dp[i - 1, j] + dp[i, j - 1]; 26 | } 27 | } 28 | return dp[m - 1, n - 1]; 29 | } 30 | 31 | // Diagonal movement allowed. 32 | public static int Unique3Ways(int m, int n) 33 | { 34 | int[,] dp = new int[m, n]; 35 | dp[0, 0] = 1; 36 | 37 | // Initialize first column. 38 | for (int i = 1; i < m; i++) 39 | { 40 | dp[i, 0] = dp[i - 1, 0]; 41 | } 42 | // Initialize first row. 43 | for (int j = 1; j < n; j++) 44 | { 45 | dp[0, j] = dp[0, j - 1]; 46 | } 47 | 48 | for (int i = 1; i < m; i++) 49 | { 50 | for (int j = 1; j < n; j++) 51 | { 52 | dp[i, j] = dp[i - 1, j - 1] + dp[i - 1, j] + dp[i, j - 1]; 53 | } 54 | } 55 | return dp[m - 1, n - 1]; 56 | } 57 | 58 | // Testing code. 59 | public static void Main(string[] args) 60 | { 61 | Console.WriteLine("UniqueWays : " + UniqueWays(3, 3)); 62 | Console.WriteLine("UniqueWays : " + Unique3Ways(3, 3)); 63 | 64 | } 65 | } 66 | 67 | /* 68 | UniqueWays : 6 69 | UniqueWays : 13 70 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/DP/LargestPalindromicSubstr.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | // Palindromic Substrings 4 | public class LargestPalindromicSubstr 5 | { 6 | public static int PalindromicSubstring(string str) 7 | { 8 | int n = str.Length; 9 | int[,] dp = new int[n, n]; 10 | for (int i = 0; i < n; i++) 11 | { 12 | dp[i, i] = 1; 13 | } 14 | 15 | int max = 1; 16 | int start = 0; 17 | 18 | for (int l = 1; l < n; l++) 19 | { 20 | for (int i = 0, j = l; j < n; i++, j++) 21 | { 22 | if (str[i] == str[j] && dp[i + 1, j - 1] == j - i - 1) 23 | { 24 | dp[i, j] = dp[i + 1, j - 1] + 2; 25 | if (dp[i, j] > max) 26 | { 27 | max = dp[i, j]; // Keeping track of max length and 28 | start = i; // starting position of sub-string. 29 | } 30 | } 31 | else 32 | { 33 | dp[i, j] = 0; 34 | } 35 | } 36 | } 37 | Console.WriteLine("Max Length Palindromic Substrings : " + str.Substring(start, max)); 38 | return max; 39 | } 40 | 41 | // Testing code. 42 | public static void Main(string[] args) 43 | { 44 | string str = "ABCAUCBCxxCBA"; 45 | Console.WriteLine("Max Palindromic Substrings len: " + PalindromicSubstring(str)); 46 | } 47 | } 48 | 49 | /* 50 | Max Length Palindromic Substrings : BCxxCB 51 | Max Palindromic Substrings len: 6 52 | */ 53 | 54 | /* 55 | //If asked to find how many different palindromic substrings are possible. 56 | int count = 0; 57 | for(int i=0;i 0) 60 | count++; 61 | return count; 62 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/Greedy/Knapsack.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | public class Knapsack 5 | { 6 | private class Items 7 | { 8 | internal int wt; 9 | internal int cost; 10 | internal double density; 11 | 12 | internal Items(int w, int v) 13 | { 14 | wt = w; 15 | cost = v; 16 | density = (double)cost / wt; 17 | } 18 | } 19 | 20 | private class DecDensity : IComparer 21 | { 22 | public int Compare(Items a, Items b) 23 | { 24 | return (int)(b.density - a.density); 25 | } 26 | } 27 | 28 | // Approximate solution. 29 | public int GetMaxCostGreedy(int[] wt, int[] cost, int capacity) 30 | { 31 | int totalCost = 0; 32 | int n = wt.Length; 33 | Items[] itemList = new Items[n]; 34 | for (int i = 0; i < n; i++) 35 | { 36 | itemList[i] = new Items(wt[i], cost[i]); 37 | } 38 | 39 | Array.Sort(itemList, new DecDensity()); 40 | for (int i = 0; i < n && capacity > 0; i++) 41 | { 42 | if (capacity - itemList[i].wt >= 0) 43 | { 44 | capacity -= itemList[i].wt; 45 | totalCost += itemList[i].cost; 46 | } 47 | } 48 | return totalCost; 49 | } 50 | 51 | // Testing code. 52 | public static void Main(string[] args) 53 | { 54 | int[] wt = new int[] {10, 40, 20, 30}; 55 | int[] cost = new int[] {60, 40, 90, 120}; 56 | int capacity = 50; 57 | 58 | Knapsack kp = new Knapsack(); 59 | int maxCost = kp.GetMaxCostGreedy(wt, cost, capacity); 60 | Console.WriteLine("Maximum cost obtained = " + maxCost); 61 | } 62 | } 63 | 64 | /* 65 | Maximum cost obtained = 150 66 | */ 67 | -------------------------------------------------------------------------------- /Stack/Stack.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class Stack 4 | { 5 | private int capacity; 6 | private int[] data; 7 | private int top = -1; 8 | 9 | public Stack(int size = 1000) 10 | { 11 | data = new int[size]; 12 | capacity = size; 13 | } 14 | /* Other methods */ 15 | 16 | public int Size() 17 | { 18 | return (top + 1); 19 | } 20 | 21 | public bool IsEmpty() 22 | { 23 | return (top == -1); 24 | } 25 | 26 | public void Push(int value) 27 | { 28 | if (Size() == capacity) 29 | { 30 | throw new System.InvalidOperationException("StackOverflowException"); 31 | } 32 | top++; 33 | data[top] = value; 34 | } 35 | 36 | public int Peek() 37 | { 38 | if (IsEmpty()) 39 | { 40 | throw new System.InvalidOperationException("StackEmptyException"); 41 | } 42 | return data[top]; 43 | } 44 | 45 | public int Pop() 46 | { 47 | if (IsEmpty()) 48 | { 49 | throw new System.InvalidOperationException("StackEmptyException"); 50 | } 51 | int topVal = data[top]; 52 | top--; 53 | return topVal; 54 | } 55 | 56 | public void Print() 57 | { 58 | for (int i = top; i > -1; i--) 59 | { 60 | Console.Write(data[i] + " "); 61 | } 62 | Console.WriteLine(); 63 | } 64 | 65 | // Testing code. 66 | public static void Main(string[] args) 67 | { 68 | Stack s = new Stack(); 69 | s.Push(1); 70 | s.Push(2); 71 | s.Push(3); 72 | s.Print(); 73 | Console.WriteLine(s.Pop()); 74 | Console.WriteLine(s.Pop()); 75 | Console.WriteLine(s.Pop()); 76 | } 77 | } 78 | /* 79 | 3 2 1 80 | 3 81 | 2 82 | 1 83 | */ -------------------------------------------------------------------------------- /Stack/StackLL.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class StackLL 4 | { 5 | private Node head = null; 6 | private int size = 0; 7 | 8 | private class Node 9 | { 10 | internal int value; 11 | internal Node next; 12 | 13 | internal Node(int v, Node n) 14 | { 15 | value = v; 16 | next = n; 17 | } 18 | } 19 | 20 | public int Size() 21 | { 22 | return size; 23 | } 24 | 25 | public bool IsEmpty() 26 | { 27 | return size == 0; 28 | } 29 | 30 | public int Peek() 31 | { 32 | if (IsEmpty()) 33 | { 34 | throw new System.InvalidOperationException("StackEmptyException"); 35 | } 36 | return head.value; 37 | } 38 | 39 | public void Push(int value) 40 | { 41 | head = new Node(value, head); 42 | size++; 43 | } 44 | 45 | public int Pop() 46 | { 47 | if (IsEmpty()) 48 | { 49 | throw new System.InvalidOperationException("StackEmptyException"); 50 | } 51 | int value = head.value; 52 | head = head.next; 53 | size--; 54 | return value; 55 | } 56 | 57 | public void Print() 58 | { 59 | Node temp = head; 60 | while (temp != null) 61 | { 62 | Console.Write(temp.value + " "); 63 | temp = temp.next; 64 | } 65 | Console.WriteLine(); 66 | } 67 | 68 | // Testing code. 69 | public static void Main(string[] args) 70 | { 71 | StackLL s = new StackLL(); 72 | s.Push(1); 73 | s.Push(2); 74 | s.Push(3); 75 | s.Print(); 76 | Console.WriteLine(s.Pop()); 77 | Console.WriteLine(s.Pop()); 78 | Console.WriteLine(s.Pop()); 79 | } 80 | } 81 | /* 82 | 3 2 1 83 | 3 84 | 2 85 | 1 86 | */ 87 | -------------------------------------------------------------------------------- /AlgorithmsChapters/Greedy/FractionalKnapsack.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class FractionalKnapsack 4 | { 5 | private class Items : IComparable 6 | { 7 | internal int wt; 8 | internal int cost; 9 | internal double density; 10 | 11 | internal Items(int w, int v) 12 | { 13 | wt = w; 14 | cost = v; 15 | density = (double)cost / wt; 16 | } 17 | 18 | public int CompareTo(Items s2) // decreasing order. 19 | { 20 | return (int)(s2.density - this.density); 21 | } 22 | } 23 | 24 | public double GetMaxCostFractional(int[] wt, int[] cost, int capacity) 25 | { 26 | double totalCost = 0; 27 | int n = wt.Length; 28 | Items[] itemList = new Items[n]; 29 | for (int i = 0; i < n; i++) 30 | { 31 | itemList[i] = new Items(wt[i], cost[i]); 32 | } 33 | 34 | Array.Sort(itemList); 35 | for (int i = 0; i < n; i++) 36 | { 37 | if (capacity - itemList[i].wt >= 0) 38 | { 39 | capacity -= itemList[i].wt; 40 | totalCost += itemList[i].cost; 41 | } 42 | else 43 | { 44 | totalCost += (itemList[i].density * capacity); 45 | break; 46 | } 47 | } 48 | return totalCost; 49 | } 50 | 51 | // Testing code. 52 | public static void Main(string[] args) 53 | { 54 | int[] wt = new int[] {10, 40, 20, 30}; 55 | int[] cost = new int[] {60, 40, 90, 120}; 56 | int capacity = 50; 57 | 58 | FractionalKnapsack kp = new FractionalKnapsack(); 59 | double maxCost = kp.GetMaxCostFractional(wt, cost, capacity); 60 | Console.WriteLine("Maximum cost obtained = " + maxCost); 61 | } 62 | } 63 | 64 | /* 65 | Maximum cost obtained = 230.0 66 | */ -------------------------------------------------------------------------------- /Sorting/QuickSelect.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class QuickSelect 4 | { 5 | public static void Select(int[] arr, int lower, int upper, int k) 6 | { 7 | if (upper <= lower) 8 | { 9 | return; 10 | } 11 | 12 | int pivot = arr[lower]; 13 | int start = lower; 14 | int stop = upper; 15 | 16 | while (lower < upper) 17 | { 18 | while (arr[lower] <= pivot && lower < upper) 19 | { 20 | lower++; 21 | } 22 | while (arr[upper] > pivot && lower <= upper) 23 | { 24 | upper--; 25 | } 26 | if (lower < upper) 27 | { 28 | Swap(arr, upper, lower); 29 | } 30 | } 31 | 32 | Swap(arr, upper, start); // upper is the pivot position 33 | if (k < upper) 34 | { 35 | Select(arr, start, upper - 1, k); // pivot -1 is the upper for 36 | } 37 | // left sub array. 38 | if (k > upper) 39 | { 40 | Select(arr, upper + 1, stop, k); // pivot + 1 is the lower for 41 | } 42 | // right sub array. 43 | } 44 | 45 | public static void Swap(int[] arr, int first, int second) 46 | { 47 | int temp = arr[first]; 48 | arr[first] = arr[second]; 49 | arr[second] = temp; 50 | } 51 | 52 | public static int Select(int[] arr, int k) 53 | { 54 | Select(arr, 0, arr.Length - 1, k - 1); 55 | return arr[k - 1]; 56 | } 57 | 58 | // Testing code. 59 | public static void Main(string[] args) 60 | { 61 | int[] array = new int[] {3, 4, 2, 1, 6, 5, 7, 8}; 62 | Console.Write("value at index 5 is : " + QuickSelect.Select(array, 5)); 63 | } 64 | } 65 | 66 | // value at index 5 is : 5 -------------------------------------------------------------------------------- /AlgorithmsChapters/DP/Fibo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class Fibo 4 | { 5 | public static int Fibonacci(int n) 6 | { 7 | if (n < 2) 8 | { 9 | return n; 10 | } 11 | return Fibonacci(n - 1) + Fibonacci(n - 2); 12 | } 13 | 14 | 15 | public static int FibonacciBU2(int n) 16 | { 17 | if (n < 2) 18 | { 19 | return n; 20 | } 21 | 22 | int first = 0, second = 1; 23 | int temp = 0; 24 | 25 | for (int i = 2; i <= n; i++) 26 | { 27 | temp = first + second; 28 | first = second; 29 | second = temp; 30 | } 31 | return temp; 32 | } 33 | 34 | public static int FibonacciBU(int n) 35 | { 36 | if (n < 2) 37 | { 38 | return n; 39 | } 40 | 41 | int[] dp = new int[n + 1]; 42 | dp[0] = 0; 43 | dp[1] = 1; 44 | 45 | for (int i = 2; i <= n; i++) 46 | { 47 | dp[i] = dp[i - 2] + dp[i - 1]; 48 | } 49 | 50 | return dp[n]; 51 | } 52 | 53 | public static int FibonacciTD(int n) 54 | { 55 | int[] dp = new int[n + 1]; 56 | FibonacciTD(n, dp); 57 | return dp[n]; 58 | } 59 | 60 | private static int FibonacciTD(int n, int[] dp) 61 | { 62 | if (n < 2) 63 | return dp[n] = n; 64 | 65 | if (dp[n] != 0) 66 | return dp[n]; 67 | 68 | dp[n] = FibonacciTD(n - 1, dp) + FibonacciTD(n - 2, dp); 69 | return dp[n]; 70 | } 71 | 72 | // Testing code. 73 | public static void Main(string[] args) 74 | { 75 | Console.WriteLine(Fibonacci(10)); 76 | Console.WriteLine(FibonacciBU2(10)); 77 | Console.WriteLine(FibonacciBU(10)); 78 | Console.WriteLine(FibonacciTD(10)); 79 | } 80 | } 81 | 82 | /* 83 | 55 84 | 55 85 | 55 86 | 55 87 | */ -------------------------------------------------------------------------------- /Sorting/MergeSort1.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class MergeSort1 4 | { 5 | private static void MergeSrt(int[] arr, int[] tempArray, int lowerIndex, int upperIndex) 6 | { 7 | if (lowerIndex >= upperIndex) 8 | { 9 | return; 10 | } 11 | int middleIndex = (lowerIndex + upperIndex) / 2; 12 | MergeSrt(arr, tempArray, lowerIndex, middleIndex); 13 | MergeSrt(arr, tempArray, middleIndex + 1, upperIndex); 14 | 15 | int lowerStart = lowerIndex; 16 | int lowerStop = middleIndex; 17 | int upperStart = middleIndex + 1; 18 | int upperStop = upperIndex; 19 | int count = lowerIndex; 20 | while (lowerStart <= lowerStop && upperStart <= upperStop) 21 | { 22 | if (arr[lowerStart] < arr[upperStart]) 23 | { 24 | tempArray[count++] = arr[lowerStart++]; 25 | } 26 | else 27 | { 28 | tempArray[count++] = arr[upperStart++]; 29 | } 30 | } 31 | while (lowerStart <= lowerStop) 32 | { 33 | tempArray[count++] = arr[lowerStart++]; 34 | } 35 | while (upperStart <= upperStop) 36 | { 37 | tempArray[count++] = arr[upperStart++]; 38 | } 39 | for (int i = lowerIndex; i <= upperIndex; i++) 40 | { 41 | arr[i] = tempArray[i]; 42 | } 43 | } 44 | 45 | public static void Sort(int[] arr) 46 | { 47 | int size = arr.Length; 48 | int[] tempArray = new int[size]; 49 | MergeSrt(arr, tempArray, 0, size - 1); 50 | } 51 | 52 | // Testing code. 53 | public static void Main(string[] args) 54 | { 55 | int[] array = new int[] {3, 4, 2, 1, 6, 5, 7, 8, 1, 1}; 56 | MergeSort1.Sort(array); 57 | for (int i = 0; i < array.Length; i++) 58 | { 59 | Console.Write(array[i] + " "); 60 | } 61 | } 62 | } -------------------------------------------------------------------------------- /AlgorithmsChapters/DP/LongestCommonSubseq.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class LongestCommonSubseq 4 | { 5 | public static int LCSubSeq(string st1, string st2) 6 | { 7 | char[] X = st1.ToCharArray(); 8 | char[] Y = st2.ToCharArray(); 9 | int m = st1.Length; 10 | int n = st2.Length; 11 | int[,] dp = new int[m + 1, n + 1]; // Dynamic programming array. 12 | int[,] p = new int[m + 1, n + 1]; // For printing the substring. 13 | 14 | // Fill dp array in bottom up fashion. 15 | for (int i = 1; i <= m; i++) 16 | { 17 | for (int j = 1; j <= n; j++) 18 | { 19 | if (X[i - 1] == Y[j - 1]) 20 | { 21 | dp[i, j] = dp[i - 1, j - 1] + 1; 22 | p[i, j] = 0; 23 | } 24 | else 25 | { 26 | dp[i, j] = (dp[i - 1, j] > dp[i, j - 1]) ? dp[i - 1, j] : dp[i, j - 1]; 27 | p[i, j] = (dp[i - 1, j] > dp[i, j - 1]) ? 1 : 2; 28 | } 29 | } 30 | } 31 | PrintLCS(p, X, m, n); 32 | Console.WriteLine(); 33 | return dp[m, n]; 34 | } 35 | 36 | private static void PrintLCS(int[,] p, char[] X, int i, int j) 37 | { 38 | if (i == 0 || j == 0) 39 | { 40 | return; 41 | } 42 | 43 | if (p[i, j] == 0) 44 | { 45 | PrintLCS(p, X, i - 1, j - 1); 46 | Console.Write(X[i - 1]); 47 | } 48 | else if (p[i, j] == 1) 49 | { 50 | PrintLCS(p, X, i - 1, j); 51 | } 52 | else 53 | { 54 | PrintLCS(p, X, i, j - 1); 55 | } 56 | } 57 | 58 | // Testing code. 59 | public static void Main(string[] args) 60 | { 61 | string X = "carpenter"; 62 | string Y = "sharpener"; 63 | Console.WriteLine(LCSubSeq(X, Y)); 64 | } 65 | } 66 | 67 | /* 68 | arpener 69 | 7 70 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/BT/TSP.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class TSP 4 | { 5 | // Function to find the minimum weight Hamiltonian Cycle 6 | private static int TSPPath(int[,] graph, int n, int[] path, int pSize, int pCost, bool[] visited, int ans, int[] ansPath) 7 | { 8 | int curr = path[pSize - 1]; 9 | if (pSize == n) 10 | { 11 | if (graph[curr, 0] > 0 && ans > pCost + graph[curr, 0]) 12 | { 13 | ans = pCost + graph[curr, 0]; 14 | for (int i = 0; i <= n; i++) 15 | ansPath[i] = path[i % n]; 16 | } 17 | return ans; 18 | } 19 | 20 | for (int i = 0; i < n; i++) 21 | { 22 | if (visited[i] == false && graph[curr, i] > 0) 23 | { 24 | visited[i] = true; 25 | path[pSize] = i; 26 | ans = TSPPath(graph, n, path, pSize + 1, pCost + graph[curr, i], visited, ans, ansPath); 27 | visited[i] = false; 28 | } 29 | } 30 | return ans; 31 | } 32 | 33 | public static int TSPPath(int[,] graph, int n) 34 | { 35 | bool[] visited = new bool[n]; 36 | int[] path = new int[n]; 37 | int[] ansPath = new int[n + 1]; 38 | 39 | path[0] = 0; 40 | visited[0] = true; 41 | int ans = int.MaxValue; 42 | ans = TSPPath(graph, n, path, 1, 0, visited, ans, ansPath); 43 | Console.WriteLine("Path length : " + ans); 44 | Console.Write("Path : "); 45 | for (int i = 0; i <= n; i++) 46 | Console.Write(ansPath[i] + " "); 47 | return ans; 48 | } 49 | 50 | // Testing code. 51 | public static void Main(string[] args) 52 | { 53 | int n = 4; 54 | int[,] graph = new int[,] 55 | { 56 | {0, 10, 15, 20}, 57 | {10, 0, 35, 25}, 58 | {15, 35, 0, 30}, 59 | {20, 25, 30, 0} 60 | }; 61 | TSPPath(graph, n); 62 | } 63 | } 64 | 65 | /* 66 | Path length : 80 67 | Path : 0 1 3 2 0 68 | */ -------------------------------------------------------------------------------- /Stack/TwoStack.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class TwoStack 4 | { 5 | private readonly int MAX_SIZE = 50; 6 | private int top1; 7 | private int top2; 8 | private int[] data; 9 | 10 | public TwoStack() 11 | { 12 | top1 = -1; 13 | top2 = MAX_SIZE; 14 | data = new int[MAX_SIZE]; 15 | } 16 | 17 | public void Push1(int value) 18 | { 19 | if (top1 < top2 - 1) 20 | { 21 | data[++top1] = value; 22 | } 23 | else 24 | { 25 | Console.Write("Stack is Full!"); 26 | } 27 | } 28 | 29 | public void Push2(int value) 30 | { 31 | if (top1 < top2 - 1) 32 | { 33 | data[--top2] = value; 34 | } 35 | else 36 | { 37 | Console.Write("Stack is Full!"); 38 | } 39 | } 40 | 41 | public int Pop1() 42 | { 43 | if (top1 >= 0) 44 | { 45 | int value = data[top1--]; 46 | return value; 47 | } 48 | else 49 | { 50 | Console.Write("Stack Empty!"); 51 | } 52 | return -999; 53 | } 54 | 55 | public int Pop2() 56 | { 57 | if (top2 < MAX_SIZE) 58 | { 59 | int value = data[top2++]; 60 | return value; 61 | } 62 | else 63 | { 64 | Console.Write("Stack Empty!"); 65 | } 66 | return -999; 67 | } 68 | 69 | // Testing code. 70 | public static void Main(string[] args) 71 | { 72 | TwoStack st = new TwoStack(); 73 | st.Push1(1); 74 | st.Push1(2); 75 | st.Push1(3); 76 | st.Push2(11); 77 | st.Push2(22); 78 | st.Push2(33); 79 | Console.WriteLine("stk1 pop: " + st.Pop1()); 80 | Console.WriteLine("stk1 pop: " + st.Pop1()); 81 | Console.WriteLine("stk2 pop: " + st.Pop2()); 82 | Console.WriteLine("stk2 pop: " + st.Pop2()); 83 | } 84 | } 85 | 86 | /* 87 | stk1 pop: 3 88 | stk1 pop: 2 89 | stk2 pop: 33 90 | stk2 pop: 22 91 | */ 92 | -------------------------------------------------------------------------------- /Sorting/SelectionSort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class SelectionSort 4 | { 5 | private bool Greater(int value1, int value2) 6 | { 7 | return value1 > value2; 8 | } 9 | 10 | public void Sort(int[] arr) // Sorted array created in reverse order. 11 | { 12 | int size = arr.Length; 13 | int i, j, max, temp; 14 | for (i = 0; i < size - 1; i++) 15 | { 16 | max = 0; 17 | for (j = 1; j < size - i; j++) 18 | { 19 | if (arr[j] > arr[max]) 20 | { 21 | max = j; 22 | } 23 | } 24 | temp = arr[size - 1 - i]; 25 | arr[size - 1 - i] = arr[max]; 26 | arr[max] = temp; 27 | } 28 | } 29 | 30 | public void Sort2(int[] arr) // Sorted array created in forward direction 31 | { 32 | int size = arr.Length; 33 | int i, j, min, temp; 34 | for (i = 0; i < size - 1; i++) 35 | { 36 | min = i; 37 | for (j = i + 1; j < size; j++) 38 | { 39 | if (arr[j] < arr[min]) 40 | { 41 | min = j; 42 | } 43 | } 44 | temp = arr[i]; 45 | arr[i] = arr[min]; 46 | arr[min] = temp; 47 | } 48 | } 49 | 50 | // Testing code. 51 | public static void Main(string[] args) 52 | { 53 | int[] array = new int[] {9, 1, 8, 2, 7, 3, 6, 4, 5}; 54 | SelectionSort srt = new SelectionSort(); 55 | srt.Sort(array); 56 | for (int i = 0; i < array.Length; i++) 57 | { 58 | Console.Write(array[i] + " "); 59 | } 60 | Console.WriteLine(); 61 | 62 | int[] array2 = new int[] {9, 1, 8, 2, 7, 3, 6, 4, 5}; 63 | srt = new SelectionSort(); 64 | srt.Sort2(array2); 65 | for (int i = 0; i < array2.Length; i++) 66 | { 67 | Console.Write(array2[i] + " "); 68 | } 69 | } 70 | } 71 | 72 | /* 73 | 1 2 3 4 5 6 7 8 9 74 | 1 2 3 4 5 6 7 8 9 75 | */ -------------------------------------------------------------------------------- /Sorting/RadixSort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class RadixSort 4 | { 5 | private int GetMax(int[] arr, int n) 6 | { 7 | int max = arr[0]; 8 | for (int i = 1; i < n; i++) 9 | { 10 | if (max < arr[i]) 11 | { 12 | max = arr[i]; 13 | } 14 | } 15 | return max; 16 | } 17 | 18 | private void CountSort(int[] arr, int n, int dividend) 19 | { 20 | int[] temp = (int[])arr.Clone(); 21 | int[] count = new int[10]; 22 | Array.Fill(count, 0); 23 | 24 | // Store count of occurrences in count array. 25 | // (number / dividend) % 10 is used to find the working digit. 26 | for (int i = 0; i < n; i++) 27 | { 28 | count[(temp[i] / dividend) % 10]++; 29 | } 30 | 31 | // Change count[i] so that count[i] contains 32 | // number of elements till index i in output. 33 | for (int i = 1; i < 10; i++) 34 | { 35 | count[i] += count[i - 1]; 36 | } 37 | 38 | // Copy content to input arr. 39 | for (int i = n - 1; i >= 0; i--) 40 | { 41 | arr[count[(temp[i] / dividend) % 10] - 1] = temp[i]; 42 | count[(temp[i] / dividend) % 10]--; 43 | } 44 | } 45 | 46 | public void Sort(int[] arr) 47 | { 48 | int n = arr.Length; 49 | int m = GetMax(arr, n); 50 | 51 | // Counting Sort for every digit. 52 | // The dividend passed is used to calculate current working digit. 53 | for (int div = 1; m / div > 0; div *= 10) 54 | { 55 | CountSort(arr, n, div); 56 | } 57 | } 58 | 59 | // Testing code. 60 | public static void Main(string[] args) 61 | { 62 | int[] array = new int[] {100, 49, 65, 91, 702, 29, 4, 55}; 63 | RadixSort b = new RadixSort(); 64 | b.Sort(array); 65 | for (int i = 0; i < array.Length; i++) 66 | { 67 | Console.Write(array[i] + " "); 68 | } 69 | } 70 | } 71 | 72 | /* 73 | 4 29 49 55 65 91 100 702 74 | */ 75 | -------------------------------------------------------------------------------- /Queue/Stack.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | public class Stack 5 | { 6 | private Queue que1 = new Queue(); 7 | private Queue que2 = new Queue(); 8 | private int size = 0; 9 | 10 | public void Push(int value) 11 | { 12 | que1.Enqueue(value); 13 | size += 1; 14 | } 15 | 16 | public int Pop() 17 | { 18 | int value = 0, s = size; 19 | while (s > 0) 20 | { 21 | value = que1.Peek(); 22 | que1.Dequeue(); 23 | if (s > 1) 24 | { 25 | que2.Enqueue(value); 26 | } 27 | s--; 28 | } 29 | Queue temp = que1; 30 | que1 = que2; 31 | que2 = temp; 32 | size -= 1; 33 | return value; 34 | } 35 | 36 | public int Pop2() 37 | { 38 | int value = 0, s = size; 39 | while (s > 0) 40 | { 41 | value = que1.Peek(); 42 | que1.Dequeue(); 43 | if (s > 1) 44 | { 45 | que1.Enqueue(value); 46 | } 47 | s--; 48 | } 49 | size -= 1; 50 | return value; 51 | } 52 | 53 | // Testing code. 54 | public static void Main1() 55 | { 56 | Stack s = new Stack(); 57 | s.Push(1); 58 | s.Push(2); 59 | s.Push(3); 60 | Console.WriteLine("Stack pop : " + s.Pop() + " "); 61 | Console.WriteLine("Stack pop : " + s.Pop() + " "); 62 | } 63 | 64 | /* 65 | Stack pop : 3 66 | Stack pop : 2 67 | */ 68 | 69 | public static void Main2() 70 | { 71 | Stack s = new Stack(); 72 | s.Push(1); 73 | s.Push(2); 74 | s.Push(3); 75 | Console.WriteLine("Stack pop : " + s.Pop2() + " "); 76 | Console.WriteLine("Stack pop : " + s.Pop2() + " "); 77 | } 78 | 79 | /* 80 | Stack pop : 3 81 | Stack pop : 2 82 | */ 83 | 84 | public static void Main(string[] args) 85 | { 86 | Main1(); 87 | Main2(); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /Sorting/BubbleSort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class BubbleSort 4 | { 5 | private bool Less(int value1, int value2) 6 | { 7 | return value1 < value2; 8 | } 9 | 10 | private bool Greater(int value1, int value2) 11 | { 12 | return value1 > value2; 13 | } 14 | 15 | public void Sort(int[] arr) 16 | { 17 | int size = arr.Length; 18 | int i, j, temp; 19 | for (i = 0; i < (size - 1); i++) 20 | { 21 | for (j = 0; j < size - i - 1; j++) 22 | { 23 | if (Greater(arr[j], arr[j + 1])) 24 | { 25 | /* Swapping */ 26 | temp = arr[j]; 27 | arr[j] = arr[j + 1]; 28 | arr[j + 1] = temp; 29 | } 30 | } 31 | } 32 | } 33 | 34 | public void Sort2(int[] arr) 35 | { 36 | int size = arr.Length; 37 | int i, j, temp, swapped = 1; 38 | for (i = 0; i < (size - 1) && swapped == 1; i++) 39 | { 40 | swapped = 0; 41 | for (j = 0; j < size - i - 1; j++) 42 | { 43 | if (Greater(arr[j], arr[j + 1])) 44 | { 45 | temp = arr[j]; 46 | arr[j] = arr[j + 1]; 47 | arr[j + 1] = temp; 48 | swapped = 1; 49 | } 50 | } 51 | } 52 | } 53 | 54 | // Testing code. 55 | public static void Main(string[] args) 56 | { 57 | int[] array = new int[] {9, 1, 8, 2, 7, 3, 6, 4, 5}; 58 | BubbleSort b = new BubbleSort(); 59 | b.Sort(array); 60 | for (int i = 0; i < array.Length; i++) 61 | { 62 | Console.Write(array[i] + " "); 63 | } 64 | Console.WriteLine(); 65 | int[] array2 = new int[] {9, 1, 8, 2, 7, 3, 6, 4, 5}; 66 | b = new BubbleSort(); 67 | b.Sort2(array2); 68 | for (int i = 0; i < array2.Length; i++) 69 | { 70 | Console.Write(array2[i] + " "); 71 | } 72 | } 73 | } 74 | /* 75 | 1 2 3 4 5 6 7 8 9 76 | 1 2 3 4 5 6 7 8 9 77 | */ -------------------------------------------------------------------------------- /Sorting/MergeSort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class MergeSort 4 | { 5 | private void Merge(int[] arr, int[] tempArray, int lowerIndex, int middleIndex, int upperIndex) 6 | { 7 | int lowerStart = lowerIndex; 8 | int lowerStop = middleIndex; 9 | int upperStart = middleIndex + 1; 10 | int upperStop = upperIndex; 11 | int count = lowerIndex; 12 | while (lowerStart <= lowerStop && upperStart <= upperStop) 13 | { 14 | if (arr[lowerStart] < arr[upperStart]) 15 | { 16 | tempArray[count++] = arr[lowerStart++]; 17 | } 18 | else 19 | { 20 | tempArray[count++] = arr[upperStart++]; 21 | } 22 | } 23 | while (lowerStart <= lowerStop) 24 | { 25 | tempArray[count++] = arr[lowerStart++]; 26 | } 27 | while (upperStart <= upperStop) 28 | { 29 | tempArray[count++] = arr[upperStart++]; 30 | } 31 | for (int i = lowerIndex; i <= upperIndex; i++) 32 | { 33 | arr[i] = tempArray[i]; 34 | } 35 | } 36 | 37 | private void MergeSrt(int[] arr, int[] tempArray, int lowerIndex, int upperIndex) 38 | { 39 | if (lowerIndex >= upperIndex) 40 | { 41 | return; 42 | } 43 | int middleIndex = (lowerIndex + upperIndex) / 2; 44 | MergeSrt(arr, tempArray, lowerIndex, middleIndex); 45 | MergeSrt(arr, tempArray, middleIndex + 1, upperIndex); 46 | Merge(arr, tempArray, lowerIndex, middleIndex, upperIndex); 47 | } 48 | 49 | public void Sort(int[] arr) 50 | { 51 | int size = arr.Length; 52 | int[] tempArray = new int[size]; 53 | MergeSrt(arr, tempArray, 0, size - 1); 54 | } 55 | 56 | // Testing code. 57 | public static void Main(string[] args) 58 | { 59 | int[] array = new int[] {3, 4, 2, 1, 6, 5, 7, 8}; 60 | MergeSort m = new MergeSort(); 61 | m.Sort(array); 62 | for (int i = 0; i < array.Length; i++) 63 | { 64 | Console.Write(array[i] + " "); 65 | } 66 | } 67 | } 68 | // 1 2 3 4 5 6 7 8 -------------------------------------------------------------------------------- /AlgorithmsChapters/Greedy/MultipleStageGraph.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class MultipleStageGraph 4 | { 5 | internal static int INF = int.MaxValue; 6 | 7 | // Returns shortest distance from 0 to N-1. 8 | public static int ShortestDist(int[, ] graph, int n) 9 | { 10 | // dist[i] is going to store shortest 11 | // distance from node i to node n-1. 12 | int[] dist = new int[n]; 13 | Array.Fill(dist, INF); 14 | int[] path = new int[n]; 15 | int value; 16 | dist[0] = 0; 17 | path[0] = -1; 18 | 19 | // Calculating shortest path for the nodes 20 | for (int i = 0; i < n; i++) 21 | { 22 | // Check all nodes of next 23 | for (int j = i; j < n; j++) 24 | { 25 | // Reject if no edge exists 26 | if (graph[i, j] == INF) 27 | { 28 | continue; 29 | } 30 | value = graph[i, j] + dist[i]; 31 | if (dist[j] > value) 32 | { 33 | dist[j] = value; 34 | path[j] = i; 35 | } 36 | } 37 | } 38 | value = n - 1; 39 | while (value != -1) 40 | { 41 | Console.Write(value + " "); 42 | value = path[value]; 43 | } 44 | Console.WriteLine(); 45 | 46 | return dist[n - 1]; 47 | } 48 | 49 | // Testing code. 50 | public static void Main(string[] args) 51 | { 52 | // Graph stored in the form of an 53 | // adjacency Matrix 54 | int[, ] graph = new int[,] 55 | { 56 | {INF, 1, 2, 5, INF, INF, INF, INF}, 57 | {INF, INF, INF, INF, 4, 11, INF, INF}, 58 | {INF, INF, INF, INF, 9, 5, 16, INF}, 59 | {INF, INF, INF, INF, INF, INF, 2, INF}, 60 | {INF, INF, INF, INF, INF, INF, INF, 18}, 61 | {INF, INF, INF, INF, INF, INF, INF, 13}, 62 | {INF, INF, INF, INF, INF, INF, INF, 2}, 63 | {INF, INF, INF, INF, INF, INF, INF, INF} 64 | }; 65 | 66 | Console.WriteLine(ShortestDist(graph, 8)); 67 | } 68 | } 69 | 70 | /* 71 | 7 6 3 0 72 | 9 73 | */ -------------------------------------------------------------------------------- /Queue/Queue.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class Queue 4 | { 5 | private int capacity; 6 | private int[] data; 7 | private int size = 0; 8 | private int front = 0; 9 | private int back = 0; 10 | 11 | public Queue(int n = 1000) 12 | { 13 | capacity = n; 14 | data = new int[n]; 15 | } 16 | 17 | public bool IsEmpty() 18 | { 19 | return size == 0; 20 | } 21 | 22 | public int Size() 23 | { 24 | return size; 25 | } 26 | 27 | public void Print() 28 | { 29 | if (size == 0) 30 | { 31 | Console.Write("Queue is empty."); 32 | return; 33 | } 34 | int temp = front; 35 | int s = size; 36 | Console.Write("Queue is : "); 37 | while (s > 0) 38 | { 39 | s--; 40 | Console.Write(data[temp] + " "); 41 | temp = (++temp) % capacity; 42 | } 43 | Console.WriteLine(); 44 | } 45 | public bool Add(int value) 46 | { 47 | if (size >= capacity) 48 | { 49 | Console.WriteLine("Queue is full."); 50 | return false; 51 | } 52 | else 53 | { 54 | size++; 55 | data[back] = value; 56 | back = (++back) % capacity; 57 | } 58 | return true; 59 | } 60 | 61 | public int Remove() 62 | { 63 | int value; 64 | if (size <= 0) 65 | { 66 | Console.WriteLine("Queue is empty."); 67 | return -999; 68 | } 69 | else 70 | { 71 | size--; 72 | value = data[front]; 73 | front = (++front) % capacity; 74 | } 75 | return value; 76 | } 77 | 78 | // Testing code. 79 | public static void Main(string[] args) 80 | { 81 | Queue que = new Queue(); 82 | que.Add(1); 83 | que.Add(2); 84 | que.Add(3); 85 | Console.WriteLine("IsEmpty : " + que.IsEmpty()); 86 | Console.WriteLine("Size : " + que.Size()); 87 | Console.WriteLine("Queue remove : " + que.Remove()); 88 | Console.WriteLine("Queue remove : " + que.Remove()); 89 | } 90 | } 91 | 92 | /* 93 | IsEmpty : False 94 | Size : 3 95 | Queue remove : 1 96 | Queue remove : 2 97 | */ -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": ".NET Core Launch (console)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "WARNING01": "*********************************************************************************", 12 | "WARNING02": "The C# extension was unable to automatically decode projects in the current", 13 | "WARNING03": "workspace to create a runnable launch.json file. A template launch.json file has", 14 | "WARNING04": "been created as a placeholder.", 15 | "WARNING05": "", 16 | "WARNING06": "If OmniSharp is currently unable to load your project, you can attempt to resolve", 17 | "WARNING07": "this by restoring any missing project dependencies (example: run 'dotnet restore')", 18 | "WARNING08": "and by fixing any reported errors from building the projects in your workspace.", 19 | "WARNING09": "If this allows OmniSharp to now load your project then --", 20 | "WARNING10": " * Delete this file", 21 | "WARNING11": " * Open the Visual Studio Code command palette (View->Command Palette)", 22 | "WARNING12": " * run the command: '.NET: Generate Assets for Build and Debug'.", 23 | "WARNING13": "", 24 | "WARNING14": "If your project requires a more complex launch configuration, you may wish to delete", 25 | "WARNING15": "this configuration and pick a different template using the 'Add Configuration...'", 26 | "WARNING16": "button at the bottom of this file.", 27 | "WARNING17": "*********************************************************************************", 28 | "preLaunchTask": "build", 29 | "program": "${workspaceFolder}/bin/Debug//.dll", 30 | "args": [], 31 | "cwd": "${workspaceFolder}", 32 | "console": "internalConsole", 33 | "stopAtEntry": false 34 | }, 35 | { 36 | "name": ".NET Core Attach", 37 | "type": "coreclr", 38 | "request": "attach" 39 | } 40 | ] 41 | } -------------------------------------------------------------------------------- /AlgorithmsChapters/DAC/NutsAndBolts.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class NutsAndBolts 4 | { 5 | private static void PrintArray(int[] arr) 6 | { 7 | Console.Write("[ "); 8 | foreach (int i in arr) 9 | { 10 | Console.Write(i + " "); 11 | } 12 | Console.WriteLine("]"); 13 | } 14 | 15 | public static void MakePairs(int[] nuts, int[] bolts) 16 | { 17 | MakePairs(nuts, bolts, 0, nuts.Length - 1); 18 | Console.WriteLine("Matched nuts and bolts are : "); 19 | PrintArray(nuts); 20 | PrintArray(bolts); 21 | } 22 | 23 | // Quick sort kind of approach. 24 | private static void MakePairs(int[] nuts, int[] bolts, int low, int high) 25 | { 26 | if (low < high) 27 | { 28 | // Choose first element of bolts array as pivot to partition nuts. 29 | int pivot = Partition(nuts, low, high, bolts[low]); 30 | 31 | // Using nuts[pivot] as pivot to partition bolts. 32 | Partition(bolts, low, high, nuts[pivot]); 33 | 34 | // Recursively lower and upper half of nuts and bolts are matched. 35 | MakePairs(nuts, bolts, low, pivot - 1); 36 | MakePairs(nuts, bolts, pivot + 1, high); 37 | } 38 | } 39 | private static void Swap(int[] arr, int first, int second) 40 | { 41 | int temp = arr[first]; 42 | arr[first] = arr[second]; 43 | arr[second] = temp; 44 | } 45 | 46 | // Partition method similar to quick sort algorithm. 47 | private static int Partition(int[] arr, int low, int high, int pivot) 48 | { 49 | int i = low; 50 | for (int j = low; j < high; j++) 51 | { 52 | if (arr[j] < pivot) 53 | { 54 | Swap(arr, i, j); 55 | i++; 56 | } 57 | else if (arr[j] == pivot) 58 | { 59 | Swap(arr, high, j); 60 | j--; 61 | } 62 | } 63 | Swap(arr, i, high); 64 | return i; 65 | } 66 | 67 | // Testing code. 68 | public static void Main(string[] args) 69 | { 70 | int[] nuts = new int[] {1, 2, 6, 5, 4, 3}; 71 | int[] bolts = new int[] {6, 4, 5, 1, 3, 2}; 72 | MakePairs(nuts, bolts); 73 | } 74 | } 75 | 76 | /* 77 | Matched nuts and bolts are : 78 | [ 1 2 3 4 5 6 ] 79 | [ 1 2 3 4 5 6 ] 80 | */ -------------------------------------------------------------------------------- /Stack/Stack2.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class Stack2 4 | { 5 | private int[] data; 6 | private int top = -1; 7 | private int minCapacity; 8 | private int capacity; 9 | 10 | public Stack2(int size = 1000) 11 | { 12 | data = new int[size]; 13 | capacity = minCapacity = size; 14 | } 15 | 16 | /* Other methods */ 17 | 18 | public int Size() 19 | { 20 | return (top + 1); 21 | } 22 | 23 | public bool IsEmpty() 24 | { 25 | return (top == -1); 26 | } 27 | 28 | public void Push(int value) 29 | { 30 | if (Size() == capacity) 31 | { 32 | Console.WriteLine("Size doubled"); 33 | int[] newData = new int[capacity * 2]; 34 | Array.Copy(data, 0, newData, 0, capacity); 35 | data = newData; 36 | capacity = capacity * 2; 37 | } 38 | top++; 39 | data[top] = value; 40 | } 41 | 42 | public int Peek() 43 | { 44 | if (IsEmpty()) 45 | { 46 | throw new System.InvalidOperationException("StackEmptyException"); 47 | } 48 | return data[top]; 49 | } 50 | 51 | public int Pop() 52 | { 53 | if (IsEmpty()) 54 | { 55 | throw new System.InvalidOperationException("StackEmptyException"); 56 | } 57 | 58 | int topVal = data[top]; 59 | top--; 60 | if (Size() == capacity / 2 && capacity > minCapacity) 61 | { 62 | Console.WriteLine("Size halved"); 63 | capacity = capacity / 2; 64 | int[] newData = new int[capacity]; 65 | Array.Copy(data, 0, newData, 0, capacity); 66 | data = newData; 67 | } 68 | return topVal; 69 | } 70 | 71 | public void Print() 72 | { 73 | for (int i = top; i > -1; i--) 74 | { 75 | Console.Write(data[i] + " "); 76 | } 77 | Console.WriteLine(); 78 | } 79 | 80 | // Testing code. 81 | public static void Main(string[] args) 82 | { 83 | Stack2 s = new Stack2(5); 84 | for (int i = 1; i <= 11; i++) 85 | { 86 | s.Push(i); 87 | } 88 | for (int i = 1; i <= 11; i++) 89 | { 90 | s.Pop(); 91 | } 92 | } 93 | } 94 | /* 95 | Size doubled 96 | Size doubled 97 | Size halved 98 | Size halved 99 | */ -------------------------------------------------------------------------------- /Sorting/BucketSort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | // Allowed values from 0 to maxValue. 5 | public class BucketSort 6 | { 7 | public void Sort(int[] arr, int maxValue) 8 | { 9 | int numBucket = 5; 10 | Sort(arr, maxValue, numBucket); 11 | } 12 | 13 | public void Sort(int[] arr, int maxValue, int numBucket) 14 | { 15 | int length = arr.Length; 16 | if (length == 0) 17 | { 18 | return; 19 | } 20 | 21 | List> bucket = new List>(numBucket); 22 | 23 | // Create empty buckets 24 | for (int i = 0; i < numBucket; i++) 25 | { 26 | bucket.Add(new List()); 27 | } 28 | 29 | int div = (int)Math.Ceiling((double)maxValue / (numBucket)); 30 | 31 | // Add elements into the buckets 32 | for (int i = 0; i < length; i++) 33 | { 34 | if (arr[i] < 0 || arr[i] > maxValue) 35 | { 36 | Console.WriteLine("Value out of range."); 37 | return; 38 | } 39 | 40 | int bucketIndex = (arr[i] / div); 41 | 42 | // Maximum value will be assigned to last bucket. 43 | if (bucketIndex >= numBucket) 44 | { 45 | bucketIndex = numBucket - 1; 46 | } 47 | 48 | bucket[bucketIndex].Add(arr[i]); 49 | } 50 | 51 | // Sort the elements of each bucket. 52 | for (int i = 0; i < numBucket; i++) 53 | { 54 | bucket[i].Sort(); 55 | } 56 | 57 | // Populate output from the Sorted subarray. 58 | int index = 0, count; 59 | for (int i = 0; i < numBucket; i++) 60 | { 61 | List temp = bucket[i]; 62 | count = temp.Count; 63 | for (int j = 0; j < count; j++) 64 | { 65 | arr[index++] = temp[j]; 66 | } 67 | } 68 | } 69 | 70 | // Testing code. 71 | public static void Main(string[] args) 72 | { 73 | int[] array = new int[] {1, 34, 7, 99, 5, 23, 45, 88, 77, 19, 91, 100}; 74 | int maxValue = 100; 75 | BucketSort b = new BucketSort(); 76 | b.Sort(array, maxValue); 77 | for (int i = 0; i < array.Length; i++) 78 | { 79 | Console.Write(array[i] + " "); 80 | } 81 | } 82 | } 83 | 84 | /* 85 | 1 5 7 19 23 34 45 77 88 91 99 100 86 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/Greedy/JobSequencing.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class JobSequencing 4 | { 5 | private Job[] jobs; 6 | private int n; 7 | private int maxDL; 8 | 9 | internal class Job 10 | { 11 | internal char id; 12 | internal int deadline, profit; 13 | 14 | internal Job(char id, int deadline, int profit) 15 | { 16 | this.id = id; 17 | this.deadline = deadline; 18 | this.profit = profit; 19 | } 20 | } 21 | 22 | public JobSequencing(char[] ids, int[] deadlines, int[] profits, int n) 23 | { 24 | this.jobs = new Job[n]; 25 | this.n = n; 26 | this.maxDL = deadlines[0]; 27 | for (int i = 1;i < n;i++) 28 | { 29 | if (deadlines[i] > this.maxDL) 30 | { 31 | this.maxDL = deadlines[i]; 32 | } 33 | } 34 | 35 | for (int i = 0;i < n;i++) 36 | { 37 | this.jobs[i] = new Job(ids[i], deadlines[i], profits[i]); 38 | } 39 | } 40 | 41 | public void Print() 42 | { 43 | Array.Sort(this.jobs, (a, b) => b.profit - a.profit); 44 | bool[] result = new bool[this.maxDL]; 45 | char[] job = new char[this.maxDL]; 46 | int profit = 0; 47 | 48 | // Iterate through all given jobs 49 | for (int i = 0; i < n; i++) 50 | { 51 | for (int j = this.jobs[i].deadline - 1; j >= 0; j--) 52 | { 53 | if (result[j] == false) 54 | { 55 | result[j] = true; 56 | job[j] = this.jobs[i].id; 57 | profit += this.jobs[i].profit; 58 | break; 59 | } 60 | } 61 | } 62 | Console.WriteLine("Profit is :: " + profit); 63 | Console.Write("Jobs selected are::"); 64 | for (int i = 0;i < this.maxDL;i++) 65 | { 66 | if (job[i] != '\u0000') 67 | { 68 | Console.Write(" " + job[i]); 69 | } 70 | } 71 | } 72 | 73 | // Testing code. 74 | public static void Main(string[] args) 75 | { 76 | char[] id = new char[] {'a', 'b', 'c', 'd', 'e'}; 77 | int[] deadline = new int[] {3, 1, 2, 4, 4}; 78 | int[] profit = new int[] {50, 40, 27, 31, 30}; 79 | JobSequencing js = new JobSequencing(id, deadline, profit, 5); 80 | js.Print(); 81 | } 82 | } 83 | 84 | /* 85 | Profit is :: 151 86 | Jobs selected are:: b e a d 87 | */ -------------------------------------------------------------------------------- /String/TST.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class TST 4 | { 5 | private Node root; 6 | 7 | private class Node 8 | { 9 | internal char data; 10 | internal bool isLastChar; 11 | internal Node left, equal, right; 12 | 13 | internal Node(char d) 14 | { 15 | data = d; 16 | isLastChar = false; 17 | left = equal = right = null; 18 | } 19 | } 20 | 21 | public void Add(string word) 22 | { 23 | root = Add(root, word, 0); 24 | } 25 | 26 | private Node Add(Node curr, string word, int wordIndex) 27 | { 28 | if (curr == null) 29 | { 30 | curr = new Node(word[wordIndex]); 31 | } 32 | 33 | if (word[wordIndex] < curr.data) 34 | { 35 | curr.left = Add(curr.left, word, wordIndex); 36 | } 37 | else if (word[wordIndex] > curr.data) 38 | { 39 | curr.right = Add(curr.right, word, wordIndex); 40 | } 41 | else if (wordIndex < word.Length - 1) 42 | { 43 | curr.equal = Add(curr.equal, word, wordIndex + 1); 44 | } 45 | else 46 | { 47 | curr.isLastChar = true; 48 | } 49 | return curr; 50 | } 51 | 52 | private bool Find(Node curr, string word, int wordIndex) 53 | { 54 | if (curr == null) 55 | { 56 | return false; 57 | } 58 | if (word[wordIndex] < curr.data) 59 | { 60 | return Find(curr.left, word, wordIndex); 61 | } 62 | else if (word[wordIndex] > curr.data) 63 | { 64 | return Find(curr.right, word, wordIndex); 65 | } 66 | else if (wordIndex == word.Length - 1) 67 | { 68 | return curr.isLastChar; 69 | } 70 | 71 | return Find(curr.equal, word, wordIndex + 1); 72 | } 73 | 74 | public bool Find(string word) 75 | { 76 | bool ret = Find(root, word, 0); 77 | return ret; 78 | } 79 | 80 | // Testing code. 81 | public static void Main(string[] args) 82 | { 83 | TST tt = new TST(); 84 | tt.Add("banana"); 85 | tt.Add("apple"); 86 | tt.Add("mango"); 87 | Console.WriteLine("Apple Found : " + tt.Find("apple")); 88 | Console.WriteLine("Banana Found : " + tt.Find("banana")); 89 | Console.WriteLine("Grapes Found : " + tt.Find("grapes")); 90 | } 91 | } 92 | /* 93 | Apple Found : True 94 | Banana Found : True 95 | Grapes Found : False 96 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/DP/FloydWarshall.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class FloydWarshall 4 | { 5 | private static readonly int INF = int.MaxValue; 6 | 7 | public static void FindAllPairPath(int[, ] graph, int V) 8 | { 9 | int[, ] dist = new int[V, V]; 10 | 11 | for (int i = 0; i < V; i++) 12 | { 13 | for (int j = 0; j < V; j++) 14 | { 15 | dist[i, j] = graph[i, j]; 16 | } 17 | } 18 | 19 | // Pick intermediate vertices. 20 | for (int k = 0; k < V; k++) 21 | { 22 | // Pick source vertices one by one. 23 | for (int i = 0; i < V; i++) 24 | { 25 | // Pick destination vertices. 26 | for (int j = 0; j < V; j++) 27 | { 28 | // If we have shorter path from i to j via k. 29 | // then update dist[i, j] 30 | if (dist[i, k] != INF && dist[k, j] != INF && dist[i, k] + dist[k, j] < dist[i, j]) 31 | { 32 | dist[i, j] = dist[i, k] + dist[k, j]; 33 | } 34 | } 35 | } 36 | } 37 | 38 | // Print the shortest distance matrix 39 | PrintSolution(dist, V); 40 | } 41 | 42 | private static void PrintSolution(int[, ] dist, int V) 43 | { 44 | for (int i = 0; i < V; i++) 45 | { 46 | for (int j = 0; j < V; j++) 47 | { 48 | if (dist[i, j] == INF) 49 | { 50 | Console.Write("INF "); 51 | } 52 | else 53 | { 54 | Console.Write(dist[i, j] + " "); 55 | } 56 | } 57 | Console.WriteLine(); 58 | } 59 | } 60 | 61 | // Testing code. 62 | public static void Main(string[] args) 63 | { 64 | int[, ] graph = new int[, ] 65 | { 66 | {0, 2, 4, INF, INF, INF, INF}, 67 | {2, 0, 4, 1, INF, INF, INF}, 68 | {4, 4, 0, 2, 8, 4, INF}, 69 | {INF, 1, 2, 0, 3, INF, 6}, 70 | {INF, INF, 6, 4, 0, 3, 1}, 71 | {INF, INF, 4, INF, 4, 0, 2}, 72 | {INF, INF, INF, 4, 2, 3, 0} 73 | }; 74 | 75 | FindAllPairPath(graph, 7); 76 | } 77 | } 78 | 79 | /* 80 | 0 2 4 3 6 8 7 81 | 2 0 3 1 4 7 5 82 | 4 3 0 2 5 4 6 83 | 3 1 2 0 3 6 4 84 | 7 5 6 4 0 3 1 85 | 8 7 4 6 4 0 2 86 | 7 5 6 4 2 3 0 87 | */ 88 | -------------------------------------------------------------------------------- /AlgorithmsChapters/DP/MinCostBinaryTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class MinCostBinaryTree 4 | { 5 | private static int MaxVal(int[,] max, int i, int j) 6 | { 7 | if (max[i, j] != int.MinValue) 8 | return max[i, j]; 9 | 10 | for (int k = i; k < j; k++) 11 | max[i, j] = Math.Max(max[i, j], Math.Max(MaxVal(max, i, k), MaxVal(max, k + 1, j))); 12 | 13 | return max[i, j]; 14 | } 15 | 16 | private static int MinCostBstTD(int[,] dp, int[,] max, int i, int j, int[] arr) 17 | { 18 | if (j <= i) 19 | return 0; 20 | 21 | if (dp[i, j] != int.MaxValue) 22 | return dp[i, j]; 23 | 24 | for (int k = i; k < j; k++) 25 | dp[i, j] = Math.Min(dp[i, j], MinCostBstTD(dp, max, i, k, arr) + MinCostBstTD(dp, max, k + 1, j, arr) + MaxVal(max, i, k) * MaxVal(max, k + 1, j)); 26 | 27 | return dp[i, j]; 28 | } 29 | 30 | public static int MinCostBstTD(int[] arr) 31 | { 32 | int n = arr.Length; 33 | int[,] dp = new int[n, n]; 34 | int[,] max = new int[n, n]; 35 | 36 | for (int i = 0; i < n; i++) 37 | { 38 | for (int j = 0; j < n; j++) 39 | { 40 | dp[i, j] = int.MaxValue; 41 | 42 | if (i != j) 43 | max[i, j] = int.MinValue; 44 | else 45 | max[i, i] = arr[i]; 46 | } 47 | } 48 | return MinCostBstTD(dp, max, 0, n - 1, arr); 49 | } 50 | 51 | public static int MinCostBstBU(int[] arr) 52 | { 53 | int n = arr.Length; 54 | int[,] dp = new int[n, n]; 55 | int[,] max = new int[n, n]; 56 | for (int i = 0; i < n; i++) 57 | max[i, i] = arr[i]; 58 | 59 | for (int l = 1; l < n; l++) // l is length of range. 60 | { 61 | for (int i = 0, j = i + l; j < n; i++, j++) 62 | { 63 | dp[i, j] = int.MaxValue; 64 | for (int k = i; k < j; k++) 65 | { 66 | dp[i, j] = Math.Min(dp[i, j], dp[i, k] + dp[k + 1, j] + max[i, k] * max[k + 1, j]); 67 | max[i, j] = Math.Max(max[i, k], max[k + 1, j]); 68 | } 69 | } 70 | } 71 | return dp[0, n - 1]; 72 | } 73 | 74 | // Testing code. 75 | public static void Main(string[] args) 76 | { 77 | int[] arr = new int[] { 6, 2, 4 }; 78 | Console.WriteLine("Total cost: " + MinCostBstTD(arr)); 79 | Console.WriteLine("Total cost: " + MinCostBstBU(arr)); 80 | } 81 | } 82 | 83 | /* 84 | Total cost: 32 85 | Total cost: 32 86 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/DP/StockBuySell.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class StockBuySell 4 | { 5 | public static int maxProfit(int[] arr) 6 | { 7 | int buyProfit = -arr[0]; // Buy stock profit 8 | int sellProfit = 0; // Sell stock profit 9 | int n = arr.Length; 10 | for (int i = 1;i < n;i++) 11 | { 12 | int newBuyProfit = (sellProfit - arr[i] > buyProfit)? sellProfit - arr[i] : buyProfit; 13 | int newSellProfit = (buyProfit + arr[i] > sellProfit)? buyProfit + arr[i] : sellProfit; 14 | buyProfit = newBuyProfit; 15 | sellProfit = newSellProfit; 16 | } 17 | return sellProfit; 18 | } 19 | 20 | public static int maxProfitTC(int[] arr, int t) 21 | { 22 | int buyProfit = -arr[0]; 23 | int sellProfit = 0; 24 | int n = arr.Length; 25 | for (int i = 1;i < n;i++) 26 | { 27 | int newBuyProfit = ((sellProfit - arr[i]) > buyProfit) ? (sellProfit - arr[i]) : buyProfit; 28 | int newSellProfit = ((buyProfit + arr[i] - t) > sellProfit) ? (buyProfit + arr[i] - t) : sellProfit; 29 | buyProfit = newBuyProfit; 30 | sellProfit = newSellProfit; 31 | } 32 | return sellProfit; 33 | } 34 | 35 | public static int maxProfit2(int[] arr) 36 | { 37 | int n = arr.Length; 38 | int[, ] dp = new int[n, 2]; 39 | dp[0, 0] = -arr[0]; // Buy stock profit 40 | dp[0, 1] = 0; // Sell stock profit 41 | 42 | for (int i = 1;i < n;i++) 43 | { 44 | dp[i, 0] = (dp[i - 1, 1] - arr[i] > dp[i - 1, 0]) ? dp[i - 1, 1] - arr[i] : dp[i - 1, 0]; 45 | dp[i, 1] = (dp[i - 1, 0] + arr[i] > dp[i - 1, 1]) ? dp[i - 1, 0] + arr[i] : dp[i - 1, 1]; 46 | } 47 | return dp[n - 1, 1]; 48 | } 49 | 50 | public static int maxProfitTC2(int[] arr, int t) 51 | { 52 | int n = arr.Length; 53 | int[, ] dp = new int[n, 2]; 54 | dp[0, 0] = -arr[0]; 55 | dp[0, 1] = 0; 56 | 57 | for (int i = 1;i < n;i++) 58 | { 59 | dp[i, 0] = ((dp[i - 1, 1] - arr[i]) > dp[i - 1, 0]) ? (dp[i - 1, 1] - arr[i]) : dp[i - 1, 0]; 60 | dp[i, 1] = ((dp[i - 1, 0] + arr[i] - t) > dp[i - 1, 1]) ? (dp[i - 1, 0] + arr[i] - t) : dp[i - 1, 1]; 61 | } 62 | return dp[n - 1, 1]; 63 | } 64 | 65 | // Testing code. 66 | public static void Main(string[] args) 67 | { 68 | int[] arr = new int[] {10, 12, 9, 23, 25, 55, 49, 70}; 69 | Console.WriteLine("Total profit: " + maxProfit(arr)); 70 | Console.WriteLine("Total profit: " + maxProfit2(arr)); 71 | Console.WriteLine("Total profit: " + maxProfitTC(arr, 2)); 72 | Console.WriteLine("Total profit: " + maxProfitTC2(arr, 2)); 73 | } 74 | } 75 | 76 | /* 77 | Total profit: 69 78 | Total profit: 69 79 | Total profit: 63 80 | Total profit: 63 81 | */ -------------------------------------------------------------------------------- /Tree/BinaryIndexTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class BinaryIndexTree 4 | { 5 | private int[] BIT; 6 | private int size; 7 | 8 | public BinaryIndexTree(int[] arr) 9 | { 10 | size = arr.Length; 11 | BIT = new int[size+1]; 12 | Array.Fill(BIT, 0); 13 | 14 | // Populating bit. 15 | for (int i = 0; i < size; i++) 16 | { 17 | Update(i, arr[i]); 18 | } 19 | } 20 | 21 | public void Set(int[] arr, int index, int val) 22 | { 23 | int diff = val - arr[index]; 24 | arr[index] = val; 25 | 26 | // Difference is propagated. 27 | Update(index, diff); 28 | } 29 | 30 | private void Update(int index, int val) 31 | { 32 | // Index in bit is 1 more than the input array. 33 | index = index + 1; 34 | 35 | // Traverse to ancestors of nodes. 36 | while (index <= size) 37 | { 38 | // Add val to current node of Binary Index Tree. 39 | BIT[index] += val; 40 | 41 | // Next element which need to store val. 42 | index += index & (-index); 43 | } 44 | } 45 | 46 | // Range sum in the range start to end. 47 | public int RangeSum(int start, int end) 48 | { 49 | // Check for error conditions. 50 | if (start > end || start < 0 || end > size - 1) 51 | { 52 | Console.WriteLine("Invalid Input."); 53 | return -1; 54 | } 55 | 56 | return PrefixSum(end) - PrefixSum(start - 1); 57 | } 58 | 59 | // Prefix sum in the range 0 to index. 60 | public int PrefixSum(int index) 61 | { 62 | int sum = 0; 63 | index = index + 1; 64 | 65 | // Traverse ancestors of Binary Index Tree nodes. 66 | while (index > 0) 67 | { 68 | // Add current element to sum. 69 | sum += BIT[index]; 70 | 71 | // Parent index calculation. 72 | index -= index & (-index); 73 | } 74 | return sum; 75 | } 76 | 77 | 78 | 79 | // Testing code. 80 | public static void Main(string[] args) 81 | { 82 | int[] arr = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; 83 | BinaryIndexTree tree = new BinaryIndexTree(arr); 84 | 85 | Console.WriteLine("Sum of elements in range(0, 5): " + tree.PrefixSum(5)); 86 | Console.WriteLine("Sum of elements in range(2, 5): " + tree.RangeSum(2, 5)); 87 | 88 | // Set fourth element to 10. 89 | tree.Set(arr, 3, 10); 90 | 91 | // Find sum after the value is Updated 92 | Console.WriteLine("Sum of elements in range(0, 5): " + tree.PrefixSum(5)); 93 | } 94 | } 95 | 96 | /* 97 | Sum of elements in range(0, 5): 21 98 | Sum of elements in range(2, 5): 18 99 | Sum of elements in range(0, 5): 27 100 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/DP/EditDist.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class EditDist 4 | { 5 | private static int Min(int x, int y, int z) 6 | { 7 | x = Math.Min(x, y); 8 | return Math.Min(x, z); 9 | } 10 | 11 | public static int FindEditDist(string str1, string str2) 12 | { 13 | int m = str1.Length; 14 | int n = str2.Length; 15 | return FindEditDist(str1, str2, m, n); 16 | } 17 | 18 | private static int FindEditDist(string str1, string str2, int m, int n) 19 | { 20 | if (m == 0 || n == 0) // If any one string is empty, then empty the other string. 21 | { 22 | return m + n; 23 | } 24 | 25 | // If last characters of both strings are same, ignore last characters. 26 | if (str1[m - 1] == str2[n - 1]) 27 | { 28 | return FindEditDist(str1, str2, m - 1, n - 1); 29 | } 30 | 31 | // If last characters are not same, 32 | // consider all three operations: 33 | // Insert last char of second into first. 34 | // Remove last char of first. 35 | // Replace last char of first with second. 36 | return 1 + Min(FindEditDist(str1, str2, m, n - 1), FindEditDist(str1, str2, m - 1, n), FindEditDist(str1, str2, m - 1, n - 1)); // Replace 37 | } 38 | 39 | public static int FindEditDistDP(string str1, string str2) 40 | { 41 | int m = str1.Length; 42 | int n = str2.Length; 43 | int[,] dp = new int[m + 1, n + 1]; 44 | 45 | // Fill dp[, ] in bottom up manner. 46 | for (int i = 0; i <= m; i++) 47 | { 48 | for (int j = 0; j <= n; j++) 49 | { 50 | // If any one string is empty, then empty the other string. 51 | if (i == 0 || j == 0) 52 | { 53 | dp[i, j] = (i + j); 54 | } 55 | // If last characters of both strings are same, ignore last characters. 56 | else if (str1[i - 1] == str2[j - 1]) 57 | { 58 | dp[i, j] = dp[i - 1, j - 1]; 59 | } 60 | // If last characters are not same, consider all three operations: 61 | // Insert last char of second into first. 62 | // Remove last char of first. 63 | // Replace last char of first with second. 64 | else 65 | { 66 | dp[i, j] = 1 + Min(dp[i, j - 1], dp[i - 1, j], dp[i - 1, j - 1]); // Replace 67 | } 68 | } 69 | } 70 | return dp[m, n]; 71 | } 72 | 73 | // Testing code. 74 | public static void Main(string[] args) 75 | { 76 | string str1 = "sunday"; 77 | string str2 = "saturday"; 78 | Console.WriteLine(FindEditDist(str1, str2)); 79 | Console.WriteLine(FindEditDistDP(str1, str2)); 80 | } 81 | } 82 | 83 | /* 84 | 3 85 | 3 86 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/DP/ALS.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class ALS 4 | { 5 | public static int FastestWayBU2(int[,] a, int[,] t, int[] e, int[] x, int n) 6 | { 7 | int[] f1 = new int[n]; 8 | int[] f2 = new int[n]; 9 | 10 | // Time taken to leave first station. 11 | f1[0] = e[0] + a[0, 0]; 12 | f2[0] = e[1] + a[1, 0]; 13 | 14 | // Fill the tables f1[] and f2[] using 15 | // bottom up approach. 16 | for (int i = 1; i < n; ++i) 17 | { 18 | f1[i] = Math.Min(f1[i - 1] + a[0, i], f2[i - 1] + t[1, i - 1] + a[0, i]); 19 | f2[i] = Math.Min(f2[i - 1] + a[1, i], f1[i - 1] + t[0, i - 1] + a[1, i]); 20 | } 21 | 22 | // Consider exit times and return minimum. 23 | return Math.Min(f1[n - 1] + x[0], f2[n - 1] + x[1]); 24 | } 25 | 26 | public static int FastestWayBU(int[,] a, int[,] t, int[] e, int[] x, int n) 27 | { 28 | int[,] f = new int[n, n]; 29 | 30 | // Time taken to leave first station. 31 | f[0, 0] = e[0] + a[0, 0]; 32 | f[1, 0] = e[1] + a[1, 0]; 33 | 34 | // Fill the tables f1[] and f2[] using 35 | // bottom up approach. 36 | for (int i = 1; i < n; ++i) 37 | { 38 | f[0, i] = Math.Min(f[0, i - 1] + a[0, i], f[1, i - 1] + t[1, i - 1] + a[0, i]); 39 | f[1, i] = Math.Min(f[1, i - 1] + a[1, i], f[0, i - 1] + t[0, i - 1] + a[1, i]); 40 | } 41 | 42 | // Consider exit times and return minimum. 43 | return Math.Min(f[0, n - 1] + x[0], f[1, n - 1] + x[1]); 44 | } 45 | 46 | 47 | public static int FastestWayTD(int[,] a, int[,] t, int[] e, int[] x, int n) 48 | { 49 | int[,] f = new int[n, n]; 50 | 51 | // Time taken to leave first station. 52 | f[0, 0] = e[0] + a[0, 0]; 53 | f[1, 0] = e[1] + a[1, 0]; 54 | 55 | FastestWayTD(f, a, t, n - 1); 56 | return Math.Min(f[0, n - 1] + x[0], f[1, n - 1] + x[1]); 57 | } 58 | 59 | private static void FastestWayTD(int[,] f, int[,] a, int[,] t, int i) 60 | { 61 | if (i == 0) 62 | { 63 | return; 64 | } 65 | FastestWayTD(f, a, t, i - 1); 66 | // Fill the tables f1[] and f2[] using top-down approach. 67 | f[0, i] = Math.Min(f[0, i - 1] + a[0, i], f[1, i - 1] + t[1, i - 1] + a[0, i]); 68 | f[1, i] = Math.Min(f[1, i - 1] + a[1, i], f[0, i - 1] + t[0, i - 1] + a[1, i]); 69 | } 70 | 71 | // Testing code. 72 | public static void Main(string[] args) 73 | { 74 | int[,] a = new int[,] { { 7, 9, 3, 4, 8, 4 }, { 8, 5, 6, 4, 5, 7 } }; 75 | int[,] t = new int[,] { { 2, 3, 1, 3, 4 }, { 2, 1, 2, 2, 1 } }; 76 | int[] e = new int[] { 2, 4 }; 77 | int[] x = new int[] { 3, 2 }; 78 | int n = 6; 79 | Console.WriteLine(FastestWayBU2(a, t, e, x, n)); 80 | Console.WriteLine(FastestWayBU(a, t, e, x, n)); 81 | Console.WriteLine(FastestWayTD(a, t, e, x, n)); 82 | } 83 | } 84 | 85 | /* 86 | 38 87 | 38 88 | 38 89 | */ -------------------------------------------------------------------------------- /Queue/QueueLL.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class QueueLL 4 | { 5 | private Node tail = null; 6 | private int size = 0; 7 | 8 | private class Node 9 | { 10 | internal int value; 11 | internal Node next; 12 | 13 | internal Node(int v, Node n) 14 | { 15 | value = v; 16 | next = n; 17 | } 18 | } 19 | 20 | public int Size() 21 | { 22 | return size; 23 | } 24 | 25 | public bool IsEmpty() 26 | { 27 | return size == 0; 28 | } 29 | 30 | public int Peek() 31 | { 32 | if (IsEmpty()) 33 | { 34 | throw new System.InvalidOperationException("StackEmptyException"); 35 | } 36 | int value; 37 | if (tail == tail.next) 38 | { 39 | value = tail.value; 40 | } 41 | else 42 | { 43 | value = tail.next.value; 44 | } 45 | 46 | return value; 47 | } 48 | 49 | public void Add(int value) 50 | { 51 | Node temp = new Node(value, null); 52 | if (tail == null) 53 | { 54 | tail = temp; 55 | tail.next = tail; 56 | } 57 | else 58 | { 59 | temp.next = tail.next; 60 | tail.next = temp; 61 | tail = temp; 62 | } 63 | size++; 64 | } 65 | 66 | public int Remove() 67 | { 68 | if (size == 0) 69 | { 70 | throw new System.InvalidOperationException("StackEmptyException"); 71 | } 72 | 73 | int value = 0; 74 | if (tail == tail.next) 75 | { 76 | value = tail.value; 77 | tail = null; 78 | } 79 | else 80 | { 81 | value = tail.next.value; 82 | tail.next = tail.next.next; 83 | } 84 | size--; 85 | return value; 86 | } 87 | 88 | public void Print() 89 | { 90 | if (size == 0) 91 | { 92 | Console.Write("Queue is empty."); 93 | return; 94 | } 95 | Node temp = tail.next; 96 | Console.Write("Queue is : "); 97 | for (int i = 0;i < size;i++) 98 | { 99 | Console.Write(temp.value + " "); 100 | temp = temp.next; 101 | } 102 | Console.WriteLine(); 103 | } 104 | 105 | // Testing code. 106 | public static void Main(string[] args) 107 | { 108 | QueueLL que = new QueueLL(); 109 | que.Add(1); 110 | que.Add(2); 111 | que.Add(3); 112 | Console.WriteLine("IsEmpty : " + que.IsEmpty()); 113 | Console.WriteLine("Size : " + que.Size()); 114 | Console.WriteLine("Queue remove : " + que.Remove()); 115 | Console.WriteLine("Queue remove : " + que.Remove()); 116 | } 117 | } 118 | /* 119 | IsEmpty : False 120 | Size : 3 121 | Queue remove : 1 122 | Queue remove : 2 123 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/BT/Permutations.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class Permutations 4 | { 5 | private static void PrintArray(int[] arr, int n) 6 | { 7 | for (int i = 0; i < n; i++) 8 | { 9 | Console.Write(arr[i] + " "); 10 | } 11 | Console.WriteLine(); 12 | } 13 | 14 | private static void Swap(int[] arr, int i, int j) 15 | { 16 | int temp = arr[i]; 17 | arr[i] = arr[j]; 18 | arr[j] = temp; 19 | } 20 | 21 | public static void Permutation(int[] arr, int i, int length) 22 | { 23 | if (length == i) 24 | { 25 | PrintArray(arr, length); 26 | return; 27 | } 28 | 29 | for (int j = i; j < length; j++) 30 | { 31 | Swap(arr, i, j); 32 | Permutation(arr, i + 1, length); 33 | Swap(arr, i, j); 34 | } 35 | return; 36 | } 37 | 38 | /* 39 | 1 2 3 4 40 | 1 2 4 3 41 | ..... 42 | 4 1 3 2 43 | 4 1 2 3 44 | */ 45 | 46 | private static bool IsValid(int[] arr, int n) 47 | { 48 | for (int j = 1; j < n; j++) 49 | { 50 | if (Math.Abs(arr[j] - arr[j - 1]) < 2) 51 | { 52 | return false; 53 | } 54 | } 55 | return true; 56 | } 57 | 58 | public static void Permutation2(int[] arr, int i, int length) 59 | { 60 | if (length == i) 61 | { 62 | if (IsValid(arr, length)) 63 | { 64 | PrintArray(arr, length); 65 | } 66 | return; 67 | } 68 | 69 | for (int j = i; j < length; j++) 70 | { 71 | Swap(arr, i, j); 72 | Permutation2(arr, i + 1, length); 73 | Swap(arr, i, j); 74 | } 75 | return; 76 | } 77 | 78 | private static bool IsValid2(int[] arr, int i) 79 | { 80 | if (i < 1 || Math.Abs(arr[i] - arr[i - 1]) >= 2) 81 | { 82 | return true; 83 | } 84 | return false; 85 | } 86 | 87 | public static void Permutation3(int[] arr, int i, int length) 88 | { 89 | if (length == i) 90 | { 91 | PrintArray(arr, length); 92 | return; 93 | } 94 | 95 | for (int j = i; j < length; j++) 96 | { 97 | Swap(arr, i, j); 98 | if (IsValid2(arr, i)) 99 | { 100 | Permutation3(arr, i + 1, length); 101 | } 102 | Swap(arr, i, j); 103 | } 104 | return; 105 | } 106 | 107 | /* Testing code */ 108 | public static void Main(string[] args) 109 | { 110 | int[] arr = { 1, 2, 3, 4 }; 111 | Permutation(arr, 0, 4); 112 | Console.WriteLine(); 113 | Permutation2(arr, 0, 4); 114 | Console.WriteLine(); 115 | Permutation3(arr, 0, 4); 116 | } 117 | } 118 | 119 | /* 120 | 2 4 1 3 121 | 3 1 4 2 122 | */ -------------------------------------------------------------------------------- /LinkedList/Polynomial.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class Polynomial 4 | { 5 | public class Node 6 | { 7 | internal int coeff; 8 | internal int pow; 9 | internal Node next; 10 | internal Node(int c, int p) 11 | { 12 | coeff = c; 13 | pow = p; 14 | next = null; 15 | } 16 | } 17 | 18 | public static Node add(Node p1, Node p2) 19 | { 20 | Node head = null, tail = null, temp = null; 21 | while (p1 != null || p2 != null) 22 | { 23 | if (p1 == null || (p2 != null && p1.pow < p2.pow)) 24 | { 25 | temp = new Node(p2.coeff, p2.pow); 26 | p2 = p2.next; 27 | } 28 | else if (p2 == null || p1.pow > p2.pow) 29 | { 30 | temp = new Node(p1.coeff, p1.pow); 31 | p1 = p1.next; 32 | } 33 | else if (p1.pow == p2.pow) 34 | { 35 | temp = new Node(p1.coeff + p2.coeff, p1.pow); 36 | p1 = p1.next; 37 | p2 = p2.next; 38 | } 39 | 40 | if (head == null) 41 | { 42 | head = tail = temp; 43 | } 44 | else 45 | { 46 | tail.next = temp; 47 | tail = tail.next; 48 | } 49 | } 50 | return head; 51 | } 52 | 53 | public static Node create(int[] coeffs, int[] pows, int size) 54 | { 55 | Node head = null, tail = null, temp = null; 56 | for (int i = 0; i < size; i++) 57 | { 58 | temp = new Node(coeffs[i], pows[i]); 59 | if (head == null) 60 | { 61 | head = tail = temp; 62 | } 63 | else 64 | { 65 | tail.next = temp; 66 | tail = tail.next; 67 | } 68 | } 69 | return head; 70 | } 71 | 72 | public static void print(Node head) 73 | { 74 | while (head != null) 75 | { 76 | Console.Write(head.coeff + "x^" + head.pow); 77 | if (head.next != null) 78 | { 79 | Console.Write(" + "); 80 | } 81 | head = head.next; 82 | } 83 | Console.WriteLine(); 84 | } 85 | 86 | // Testing code. 87 | public static void Main(string[] args) 88 | { 89 | int[] c1 = new int[] {6, 5, 4}; 90 | int[] p1 = new int[] {2, 1, 0}; 91 | int s1 = c1.Length; 92 | Node first = create(c1, p1, s1); 93 | print(first); 94 | 95 | int[] c2 = new int[] {3, 2, 1}; 96 | int[] p2 = new int[] {3, 1, 0}; 97 | int s2 = c2.Length; 98 | Node second = create(c2, p2, s2); 99 | print(second); 100 | 101 | Node sum = add(first, second); 102 | print(sum); 103 | } 104 | } 105 | 106 | /* 107 | 6x^2 + 5x^1 + 4x^0 108 | 3x^3 + 2x^1 + 1x^0 109 | 3x^3 + 6x^2 + 7x^1 + 5x^0 110 | */ -------------------------------------------------------------------------------- /String/Trie.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class Trie 4 | { 5 | private const int CharCount = 26; 6 | private Node root = null; 7 | 8 | private class Node 9 | { 10 | internal bool isLastChar; 11 | internal Node[] child; 12 | 13 | internal Node(char c) 14 | { 15 | child = new Node[CharCount]; 16 | for (int i = 0; i < CharCount; i++) 17 | { 18 | child[i] = null; 19 | } 20 | isLastChar = false; 21 | } 22 | } 23 | 24 | public Trie() 25 | { 26 | root = new Node(' '); 27 | } 28 | 29 | public void Add(string str) 30 | { 31 | if (str == null) 32 | return; 33 | Add(root, str.ToLower(), 0); 34 | } 35 | 36 | private Node Add(Node curr, string str, int index) 37 | { 38 | if (curr == null) 39 | { 40 | curr = new Node(str[index - 1]); 41 | } 42 | 43 | if (str.Length == index) 44 | { 45 | curr.isLastChar = true; 46 | } 47 | else 48 | { 49 | curr.child[str[index] - 'a'] = Add(curr.child[str[index] - 'a'], str, index + 1); 50 | } 51 | return curr; 52 | } 53 | 54 | public void Remove(string str) 55 | { 56 | if (string.ReferenceEquals(str, null)) 57 | { 58 | return; 59 | } 60 | str = str.ToLower(); 61 | Remove(root, str, 0); 62 | } 63 | 64 | private void Remove(Node curr, string str, int index) 65 | { 66 | if (curr == null) 67 | { 68 | return; 69 | } 70 | if (str.Length == index) 71 | { 72 | if (curr.isLastChar) 73 | { 74 | curr.isLastChar = false; 75 | } 76 | return; 77 | } 78 | Remove(curr.child[str[index] - 'a'], str, index + 1); 79 | } 80 | 81 | public bool Find(string str) 82 | { 83 | if (string.ReferenceEquals(str, null)) 84 | { 85 | return false; 86 | } 87 | str = str.ToLower(); 88 | return Find(root, str, 0); 89 | } 90 | 91 | private bool Find(Node curr, string str, int index) 92 | { 93 | if (curr == null) 94 | { 95 | return false; 96 | } 97 | if (str.Length == index) 98 | { 99 | return curr.isLastChar; 100 | } 101 | return Find(curr.child[str[index] - 'a'], str, index + 1); 102 | } 103 | 104 | // Testing code. 105 | public static void Main(string[] args) 106 | { 107 | Trie tt = new Trie(); 108 | tt.Add("banana"); 109 | tt.Add("apple"); 110 | tt.Add("mango"); 111 | Console.WriteLine("Apple Found : " + tt.Find("apple")); 112 | Console.WriteLine("Banana Found : " + tt.Find("banana")); 113 | Console.WriteLine("Grapes Found : " + tt.Find("grapes")); 114 | } 115 | } 116 | /* 117 | Apple Found : True 118 | Banana Found : True 119 | Grapes Found : False 120 | */ -------------------------------------------------------------------------------- /FENWICK/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | class FenWickTree{ 3 | int size; 4 | float[] sum; 5 | 6 | public FenWickTree(float[] input, int n) 7 | { 8 | size = n; 9 | sum = new float[size+1]; 10 | for(int i =0;i0) 31 | { 32 | total += sum[index]; 33 | index -= index & (-index); 34 | } 35 | return total; 36 | } 37 | } 38 | 39 | class InventoryManager{ 40 | FenWickTree tree; 41 | 42 | public InventoryManager(int size){ 43 | 44 | float[] arr = new float[size]; 45 | tree = new FenWickTree(arr, size); 46 | } 47 | 48 | public void AddSupply(int bucket, float delta){ 49 | tree.add(bucket, delta); 50 | } 51 | 52 | public void AddDemand(int bucket, float delta){ 53 | tree.add(bucket, -1*delta); 54 | } 55 | 56 | public float GetInventory(int bucket){ 57 | return tree.getPrefixSum(bucket); 58 | } 59 | } 60 | 61 | class Program 62 | { 63 | 64 | // Testing code. 65 | static void Main(string[] args) 66 | { 67 | InventoryManager im = new InventoryManager(10); 68 | im.AddSupply(2, 50); 69 | 70 | Console.WriteLine(im.GetInventory(6)); 71 | im.AddDemand(3, 25); 72 | Console.WriteLine(im.GetInventory(6)); 73 | im.AddDemand(2, 30); 74 | Console.WriteLine(im.GetInventory(6)); 75 | } 76 | } 77 | /* 78 | static void Main(string[] args) 79 | { 80 | int []input = {2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9}; 81 | int size = input.Length; 82 | FenWickTree tree = new FenWickTree(input, size); 83 | 84 | Console.WriteLine("Sum of elements in arr[0..5] is "+ tree.getSufixSum(5)); 85 | 86 | tree.add(3, 6); 87 | 88 | Console.WriteLine("Sum of elements in arr[0..5] after update is " + tree.getSufixSum(5)); 89 | tree.remove(3, 6); 90 | Console.WriteLine("Sum of elements in arr[0..5] after update is " + tree.getSufixSum(5)); 91 | 92 | } 93 | static void Main(string[] args) 94 | { 95 | float []input = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; 96 | int size = input.Length; 97 | FenWickTree tree = new FenWickTree(input, size); 98 | tree.add(2, 50); 99 | Console.WriteLine(tree.getPrefixSum(6)); 100 | tree.remove(3, 25); 101 | Console.WriteLine(tree.getPrefixSum(6)); 102 | tree.remove(2, 30); 103 | Console.WriteLine(tree.getPrefixSum(6)); 104 | } */ 105 | /* 106 | public void remove(int index, float val) 107 | { 108 | add(index , -1*val); 109 | } */ 110 | 111 | 112 | -------------------------------------------------------------------------------- /Searching/BitManipulation.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class BitManipulation 4 | { 5 | public static int AndEx(int a, int b) 6 | { 7 | return a & b; 8 | } 9 | 10 | public static int OrEx(int a, int b) 11 | { 12 | return a | b; 13 | } 14 | 15 | public static int XorEx(int a, int b) 16 | { 17 | return a ^ b; 18 | } 19 | 20 | public static int LeftShiftEx(int a) // multiply by 2 21 | { 22 | return a << 1; 23 | } 24 | 25 | public static int RightShiftEx(int a) // divide by 2 26 | { 27 | return a >> 1; 28 | } 29 | 30 | public static int BitReversalEx(int a) 31 | { 32 | return ~a; 33 | } 34 | 35 | public static int TwosComplementEx(int a) 36 | { 37 | return -a; 38 | } 39 | 40 | public static bool KthBitCheck(int a, int k) 41 | { 42 | return (a & 1 << (k - 1)) > 0; 43 | } 44 | 45 | public static int KthBitSet(int a, int k) 46 | { 47 | return (a | 1 << (k - 1)); 48 | } 49 | 50 | public static int KthBitReset(int a, int k) 51 | { 52 | return (a & ~(1 << (k - 1))); 53 | } 54 | 55 | public static int KthBitToggle(int a, int k) 56 | { 57 | return (a ^ (1 << (k - 1))); 58 | } 59 | 60 | public static int RightMostBit(int a) 61 | { 62 | return a & -a; 63 | } 64 | 65 | public static int ResetRightMostBit(int a) 66 | { 67 | return a & (a - 1); 68 | } 69 | 70 | public static bool IsPowerOf2(int a) 71 | { 72 | if ((a & (a - 1)) == 0) 73 | { 74 | return true; 75 | } 76 | else 77 | { 78 | return false; 79 | } 80 | } 81 | 82 | public static int CountBits(int a) 83 | { 84 | int count = 0; 85 | while (a > 0) 86 | { 87 | count += 1; 88 | a = a & (a - 1); // reset least significant bit. 89 | } 90 | return count; 91 | } 92 | 93 | // Testing code. 94 | public static void Main(string[] args) 95 | { 96 | int a = 4; 97 | int b = 8; 98 | 99 | Console.WriteLine(AndEx(a, b)); 100 | Console.WriteLine(OrEx(a, b)); 101 | Console.WriteLine(XorEx(a, b)); 102 | Console.WriteLine(LeftShiftEx(a)); // multiply by 2 103 | Console.WriteLine(RightShiftEx(a)); // divide by 2 104 | Console.WriteLine(BitReversalEx(a)); 105 | Console.WriteLine(TwosComplementEx(a)); 106 | Console.WriteLine(KthBitCheck(a, 3)); 107 | Console.WriteLine(KthBitSet(a, 2)); 108 | Console.WriteLine(KthBitReset(a, 3)); 109 | Console.WriteLine(KthBitToggle(a, 3)); 110 | Console.WriteLine(RightMostBit(a)); 111 | Console.WriteLine(ResetRightMostBit(a)); 112 | Console.WriteLine(IsPowerOf2(a)); 113 | 114 | for (int i = 0;i < 10;i++) 115 | { 116 | Console.WriteLine(i + " bit count : " + CountBits(i)); 117 | } 118 | } 119 | } 120 | 121 | /* 122 | 0 123 | 12 124 | 12 125 | 8 126 | 2 127 | -5 128 | -4 129 | True 130 | 6 131 | 0 132 | 0 133 | 4 134 | 0 135 | True 136 | */ 137 | 138 | /* 139 | 0 bit count : 0 140 | 1 bit count : 1 141 | 2 bit count : 1 142 | 3 bit count : 2 143 | 4 bit count : 1 144 | 5 bit count : 2 145 | 6 bit count : 2 146 | 7 bit count : 3 147 | 8 bit count : 1 148 | 9 bit count : 2 149 | */ -------------------------------------------------------------------------------- /String/StringTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class StringTree 4 | { 5 | private Node root = null; 6 | 7 | private class Node 8 | { 9 | internal string value; 10 | internal int count; 11 | internal Node lChild; 12 | internal Node rChild; 13 | } 14 | 15 | // Other Methods. 16 | public void Print() 17 | { 18 | Print(root); 19 | } 20 | 21 | private void Print(Node curr) // pre order 22 | { 23 | if (curr != null) 24 | { 25 | Console.Write(" value is ::" + curr.value); 26 | Console.WriteLine(" count is :: " + curr.count); 27 | Print(curr.lChild); 28 | Print(curr.rChild); 29 | } 30 | } 31 | 32 | public void Add(string value) 33 | { 34 | root = Add(value, root); 35 | } 36 | 37 | private Node Add(string value, Node curr) 38 | { 39 | if (curr == null) 40 | { 41 | curr = new Node(); 42 | curr.value = value; 43 | curr.lChild = curr.rChild = null; 44 | curr.count = 1; 45 | } 46 | else 47 | { 48 | int compare = string.CompareOrdinal(curr.value, value); 49 | if (compare == 0) 50 | { 51 | curr.count++; 52 | } 53 | else if (compare == 1) 54 | { 55 | curr.lChild = Add(value, curr.lChild); 56 | } 57 | else 58 | { 59 | curr.rChild = Add(value, curr.rChild); 60 | } 61 | } 62 | return curr; 63 | } 64 | 65 | public bool Find(string value) 66 | { 67 | return Find(root, value); 68 | } 69 | 70 | private bool Find(Node curr, string value) 71 | { 72 | if (curr == null) 73 | { 74 | return false; 75 | } 76 | int compare = string.CompareOrdinal(curr.value, value); 77 | if (compare == 0) 78 | { 79 | return true; 80 | } 81 | 82 | if (compare == 1) 83 | { 84 | return Find(curr.lChild, value); 85 | } 86 | 87 | return Find(curr.rChild, value); 88 | } 89 | 90 | public int Frequency(string value) 91 | { 92 | return Frequency(root, value); 93 | } 94 | 95 | private int Frequency(Node curr, string value) 96 | { 97 | if (curr == null) 98 | { 99 | return 0; 100 | } 101 | 102 | int compare = string.CompareOrdinal(curr.value, value); 103 | if (compare == 0) 104 | { 105 | return curr.count; 106 | } 107 | 108 | if (compare > 0) 109 | { 110 | return Frequency(curr.lChild, value); 111 | } 112 | 113 | return Frequency(curr.rChild, value); 114 | } 115 | 116 | public void FreeTree() 117 | { 118 | root = null; 119 | } 120 | 121 | // Testing code. 122 | public static void Main(string[] args) 123 | { 124 | StringTree tt = new StringTree(); 125 | tt.Add("banana"); 126 | tt.Add("apple"); 127 | tt.Add("mango"); 128 | Console.WriteLine("Apple Found : " + tt.Find("apple")); 129 | Console.WriteLine("Banana Found : " + tt.Find("banana")); 130 | Console.WriteLine("Grapes Found : " + tt.Find("grapes")); 131 | 132 | } 133 | } 134 | 135 | /* 136 | Apple Found : True 137 | Banana Found : True 138 | Grapes Found : False 139 | */ -------------------------------------------------------------------------------- /HashTable/HashTableSC.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class HashTableSC 4 | { 5 | private int tableSize; 6 | private Node[] listArray; 7 | 8 | private class Node 9 | { 10 | internal int key; 11 | internal int value; 12 | internal Node next; 13 | 14 | public Node(int k, int v, Node n) 15 | { 16 | key = k; 17 | value = v; 18 | next = n; 19 | } 20 | } 21 | 22 | public HashTableSC() 23 | { 24 | tableSize = 512; 25 | listArray = new Node[tableSize]; 26 | Array.Fill(listArray, null); 27 | } 28 | 29 | private int ComputeHash(int key) // division method 30 | { 31 | int hashValue = key; 32 | return hashValue % tableSize; 33 | } 34 | 35 | public void Add(int key, int value) 36 | { 37 | int index = ComputeHash(key); 38 | listArray[index] = new Node(key, value, listArray[index]); 39 | } 40 | 41 | public void Add(int value) 42 | { 43 | Add(value, value); 44 | } 45 | 46 | public bool Remove(int key) 47 | { 48 | int index = ComputeHash(key); 49 | Node nextNode, head = listArray[index]; 50 | if (head != null && head.key == key) 51 | { 52 | listArray[index] = head.next; 53 | return true; 54 | } 55 | while (head != null) 56 | { 57 | nextNode = head.next; 58 | if (nextNode != null && nextNode.key == key) 59 | { 60 | head.next = nextNode.next; 61 | return true; 62 | } 63 | else 64 | { 65 | head = nextNode; 66 | } 67 | } 68 | return false; 69 | } 70 | 71 | public void Print() 72 | { 73 | Console.Write("Hash Table contains ::"); 74 | for (int i = 0; i < tableSize; i++) 75 | { 76 | Node head = listArray[i]; 77 | while (head != null) 78 | { 79 | Console.Write("(" + head.key + "=>" + head.value + ") "); 80 | head = head.next; 81 | } 82 | } 83 | Console.WriteLine(); 84 | } 85 | 86 | public bool Find(int key) 87 | { 88 | int index = ComputeHash(key); 89 | Node head = listArray[index]; 90 | while (head != null) 91 | { 92 | if (head.key == key) 93 | { 94 | return true; 95 | } 96 | head = head.next; 97 | } 98 | return false; 99 | } 100 | 101 | public int Get(int key) 102 | { 103 | int index = ComputeHash(key); 104 | Node head = listArray[index]; 105 | while (head != null) 106 | { 107 | if (head.key == key) 108 | { 109 | return head.value; 110 | } 111 | head = head.next; 112 | } 113 | return -1; 114 | } 115 | 116 | // Testing code. 117 | public static void Main(string[] args) 118 | { 119 | HashTableSC ht = new HashTableSC(); 120 | ht.Add(1, 10); 121 | ht.Add(2, 20); 122 | ht.Add(3, 30); 123 | ht.Print(); 124 | Console.WriteLine("Find key 2 : " + ht.Find(2)); 125 | Console.WriteLine("Value at key 2 : " + ht.Get(2)); 126 | ht.Remove(2); 127 | Console.WriteLine("Find key 2 : " + ht.Find(2)); 128 | ht.Print(); 129 | } 130 | } 131 | 132 | /* 133 | Hash Table contains ::(1=>10) (2=>20) (3=>30) 134 | Find key 2 : True 135 | Value at key 2 : 20 136 | Find key 2 : False 137 | Hash Table contains ::(1=>10) (3=>30) 138 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/DAC/ClosestPair.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | public class ClosestPair 5 | { 6 | public class Point 7 | { 8 | internal int x, y; 9 | internal Point(int a, int b) 10 | { 11 | x = a; 12 | y = b; 13 | } 14 | } 15 | 16 | private static double Distance(Point a, Point b) 17 | { 18 | return Math.Sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)); 19 | } 20 | 21 | internal class xComp : IComparer 22 | { 23 | public int Compare(Point s1, Point s2) 24 | { 25 | return (s1.x - s2.x); 26 | } 27 | } 28 | 29 | internal class yComp : IComparer 30 | { 31 | public int Compare(Point s1, Point s2) 32 | { 33 | return (s1.y - s2.y); 34 | } 35 | } 36 | 37 | private static double StripMin(Point[] q, int n, double d) 38 | { 39 | double min = d; 40 | 41 | // Find the Distance between all the points in the strip. 42 | // Array q is sorted according to the y axis coordinate. 43 | // The inner loop will run at most 6 times for each point. 44 | for (int i = 0; i < n; ++i) 45 | { 46 | for (int j = i + 1; j < n && (q[j].y - q[i].y) < min; ++j) 47 | { 48 | d = Distance(q[i], q[j]); 49 | if (d < min) 50 | { 51 | min = d; 52 | } 53 | } 54 | } 55 | return min; 56 | } 57 | 58 | private double ClosestPairUtil(Point[] p, int start, int stop, Point[] q, int n) 59 | { 60 | if (stop - start < 1) 61 | { 62 | return double.MaxValue; 63 | } 64 | 65 | if (stop - start == 1) 66 | { 67 | return Distance(p[start], p[stop]); 68 | } 69 | 70 | // Find the middle point 71 | int mid = (start + stop) / 2; 72 | 73 | double dl = ClosestPairUtil(p, start, mid, q, n); 74 | double dr = ClosestPairUtil(p, mid + 1, stop, q, n); 75 | double d = Math.Min(dl, dr); 76 | 77 | // Build an array strip[] that contains points whose x axis coordinate 78 | // in the range p[mid]-d and p[mid]+d. 79 | // Points are already sorted according to y axis. 80 | Point[] strip = new Point[n]; 81 | int j = 0; 82 | for (int i = 0; i < n; i++) 83 | { 84 | if (Math.Abs(q[i].x - p[mid].x) < d) 85 | { 86 | strip[j] = q[i]; 87 | j++; 88 | } 89 | } 90 | // Find the closest points in strip and compare with d. 91 | return Math.Min(d, StripMin(strip, j, d)); 92 | } 93 | 94 | 95 | public double ClosestPairDC(int[,] arr) 96 | { 97 | int n = arr.GetLength(0); 98 | Point[] p = new Point[n]; 99 | for (int i = 0; i < n; i++) 100 | { 101 | p[i] = new Point(arr[i, 0], arr[i, 1]); 102 | } 103 | // Sort according to x axis. 104 | Array.Sort(p, new xComp()); 105 | 106 | Point[] q = (ClosestPair.Point[])p.Clone(); 107 | // Sort according to y axis. 108 | Array.Sort(q, new yComp()); 109 | return ClosestPairUtil(p, 0, n - 1, q, n); 110 | } 111 | 112 | // Testing code. 113 | public static void Main(string[] args) 114 | { 115 | int[,] arr = new int[,] { { 648, 896 }, { 269, 879 }, { 250, 922 }, { 453, 347 }, { 213, 17 } }; 116 | ClosestPair cp = new ClosestPair(); 117 | Console.WriteLine("Smallest Distance is:" + cp.ClosestPairBF(arr)); 118 | Console.WriteLine("Smallest Distance is:" + cp.ClosestPairDC(arr)); 119 | } 120 | } 121 | 122 | /* 123 | Smallest Distance is:47.0106370941726 124 | Smallest Distance is:47.0106370941726 125 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/DP/WildCharMatch.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class WildCharMatch 4 | { 5 | public static bool MatchExp(string exp, string str) 6 | { 7 | return MatchExpUtil(exp.ToCharArray(), str.ToCharArray(), 0, 0); 8 | } 9 | 10 | private static bool MatchExpUtil(char[] exp, char[] str, int m, int n) 11 | { 12 | if (m == exp.Length && (n == str.Length || exp[m - 1] == '*')) 13 | { 14 | return true; 15 | } 16 | if ((m == exp.Length && n != str.Length) || (m != exp.Length && n == str.Length)) 17 | { 18 | return false; 19 | } 20 | if (exp[m] == '?' || exp[m] == str[n]) 21 | { 22 | return MatchExpUtil(exp, str, m + 1, n + 1); 23 | } 24 | if (exp[m] == '*') 25 | { 26 | return MatchExpUtil(exp, str, m + 1, n) || MatchExpUtil(exp, str, m, n + 1); 27 | } 28 | return false; 29 | } 30 | 31 | public static bool MatchExpDP(string exp, string str) 32 | { 33 | return MatchExpUtilDP(exp.ToCharArray(), str.ToCharArray(), exp.Length, str.Length); 34 | } 35 | 36 | private static bool MatchExpUtilDP(char[] exp, char[] str, int m, int n) 37 | { 38 | bool[,] lookup = new bool[m + 1, n + 1]; 39 | lookup[0, 0] = true; // empty exp and empty str match. 40 | 41 | // 0 row will remain all false. empty exp can't match any str. 42 | // '*' can match with empty string, column 0 update. 43 | for (int i = 1; i <= m; i++) 44 | { 45 | if (exp[i - 1] == '*') 46 | { 47 | lookup[i, 0] = lookup[i - 1, 0]; 48 | } 49 | else 50 | { 51 | break; 52 | } 53 | } 54 | 55 | // Fill the table in bottom-up fashion 56 | for (int i = 1; i <= m; i++) 57 | { 58 | for (int j = 1; j <= n; j++) 59 | { 60 | // If we see a '*' in pattern: 61 | // 1) We ignore '*' character and consider 62 | // next character in the pattern. 63 | // 2) We ignore one character in the input str 64 | // and consider next character. 65 | if (exp[i - 1] == '*') 66 | { 67 | lookup[i, j] = lookup[i - 1, j] || lookup[i, j - 1]; 68 | } 69 | // Condition when both the pattern and input string 70 | // have same character. Also '?' match with all the 71 | // characters. 72 | else if (exp[i - 1] == '?' || str[j - 1] == exp[i - 1]) 73 | { 74 | lookup[i, j] = lookup[i - 1, j - 1]; 75 | } 76 | // If characters don't match 77 | else 78 | { 79 | lookup[i, j] = false; 80 | } 81 | } 82 | } 83 | return lookup[m, n]; 84 | } 85 | 86 | // Testing code. 87 | public static void Main(string[] args) 88 | { 89 | Console.WriteLine("MatchExp :: " + MatchExp("*llo,?World?", "Hello, World!")); 90 | Console.WriteLine("MatchExp :: " + MatchExpDP("*llo,?World?", "Hello, World!")); 91 | } 92 | /* 93 | MatchExp :: True 94 | MatchExp :: True 95 | */ 96 | 97 | // Testing code. 98 | public static void main2(string[] args) 99 | { 100 | string str = "baaabab"; 101 | string[] pattern = new string[] { "*****ba*****ab", "ba*****ab", "ba*ab", "a*ab", "a*****ab", "*a*****ab", "ba*ab****", "****", "*", "aa?ab", "b*b", "a*a", "baaabab", "?baaabab", "*baaaba*" }; 102 | 103 | foreach (string p in pattern) 104 | { 105 | if (MatchExp(p, str) != MatchExpDP(p, str)) 106 | { 107 | Console.Write(MatchExpDP(p, str) + " for "); 108 | Console.WriteLine(p + " == " + str); 109 | } 110 | } 111 | } 112 | } -------------------------------------------------------------------------------- /AlgorithmsChapters/BT/GraphColouring.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class GraphColouring 4 | { 5 | // Is it safe to colour vth vertice with c colour. 6 | private static bool IsSafe(bool[,] graph, int V, int[] colour, int v, int c) 7 | { 8 | for (int i = 0; i < V; i++) 9 | { 10 | if (graph[v, i] == true && c == colour[i]) 11 | { 12 | return false; 13 | } 14 | } 15 | return true; 16 | } 17 | 18 | private static bool ColouringUtil(bool[,] graph, int V, int m, int[] colour, int i) 19 | { 20 | if (i == V) 21 | { 22 | PrintSolution(colour, V); 23 | return true; 24 | } 25 | 26 | for (int j = 1; j <= m; j++) 27 | { 28 | if (IsSafe(graph, V, colour, i, j)) 29 | { 30 | colour[i] = j; 31 | if (ColouringUtil(graph, V, m, colour, i + 1)) 32 | { 33 | return true; 34 | } 35 | } 36 | } 37 | return false; 38 | } 39 | 40 | public static bool Colouring(bool[,] graph, int V, int m) 41 | { 42 | int[] colour = new int[V]; 43 | if (ColouringUtil(graph, V, m, colour, 0)) 44 | { 45 | return true; 46 | } 47 | return false; 48 | } 49 | 50 | private static void PrintSolution(int[] colour, int V) 51 | { 52 | Console.Write("Assigned colours are::"); 53 | for (int i = 0; i < V; i++) 54 | { 55 | Console.Write(" " + colour[i]); 56 | } 57 | Console.WriteLine(); 58 | } 59 | 60 | // Check if the whole graph is coloured properly. 61 | private static bool IsSafe2(bool[,] graph, int[] colour, int V) 62 | { 63 | for (int i = 0; i < V; i++) 64 | { 65 | for (int j = i + 1; j < V; j++) 66 | { 67 | if (graph[i, j] && colour[j] == colour[i]) 68 | { 69 | return false; 70 | } 71 | } 72 | } 73 | return true; 74 | } 75 | 76 | private static bool Colouring2(bool[,] graph, int V, int m, int[] colour, int i) 77 | { 78 | if (i == V) 79 | { 80 | if (IsSafe2(graph, colour, V)) 81 | { 82 | PrintSolution(colour, V); 83 | return true; 84 | } 85 | return false; 86 | } 87 | 88 | // Assign each colour from 1 to m 89 | for (int j = 1; j <= m; j++) 90 | { 91 | colour[i] = j; 92 | if (Colouring2(graph, V, m, colour, i + 1)) 93 | { 94 | return true; 95 | } 96 | } 97 | return false; 98 | } 99 | 100 | public static bool Colouring2(bool[,] graph, int V, int m) 101 | { 102 | int[] colour = new int[V]; 103 | if (Colouring2(graph, V, m, colour, 0)) 104 | { 105 | return true; 106 | } 107 | return false; 108 | } 109 | 110 | // Testing code. 111 | public static void Main(string[] args) 112 | { 113 | bool[,] graph = new bool[,] 114 | { 115 | {false, true, false, false, true}, 116 | {true, false, true, false, true}, 117 | {false, true, false, true, true}, 118 | {false, false, true, false, true}, 119 | {true, true, true, true, false} 120 | }; 121 | int V = 5; // Number of vertices 122 | int m = 4; // Number of colours 123 | if (!GraphColouring.Colouring2(graph, V, m)) 124 | { 125 | Console.WriteLine("Solution does not exist"); 126 | } 127 | if (!GraphColouring.Colouring(graph, V, m)) 128 | { 129 | Console.WriteLine("Solution does not exist"); 130 | } 131 | } 132 | } 133 | /* 134 | Assigned colours are:: 1 2 1 2 3 135 | Assigned colours are:: 1 2 1 2 3 136 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/DP/JobScheduling.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | // Also known as Activity Selection Weighted. 4 | public class JobScheduling 5 | { 6 | public class Job : IComparable 7 | { 8 | internal int start, stop, value; 9 | 10 | internal Job(int s, int f, int v) 11 | { 12 | start = s; 13 | stop = f; 14 | value = v; 15 | } 16 | 17 | public int CompareTo(Job j2) 18 | { 19 | return this.stop - j2.stop; 20 | } 21 | } 22 | 23 | public static int MaxValueJobsUtil(Job[] arr, int n) 24 | { 25 | // Base case 26 | if (n == 1) 27 | { 28 | return arr[0].value; 29 | } 30 | 31 | // Find Value when current job is included 32 | int incl = arr[n - 1].value; 33 | for (int j = n - 1; j >= 0; j--) 34 | { 35 | if (arr[j].stop <= arr[n - 1].start) 36 | { 37 | incl += MaxValueJobsUtil(arr, j + 1); 38 | break; 39 | } 40 | } 41 | 42 | // Find Value when current job is excluded 43 | int excl = MaxValueJobsUtil(arr, n - 1); 44 | 45 | return Math.Max(incl, excl); 46 | } 47 | 48 | 49 | public static int MaxValueJobs(int[] s, int[] f, int[] v, int n) 50 | { 51 | Job[] act = new Job[n]; 52 | for (int i = 0;i < n;i++) 53 | { 54 | act[i] = new Job(s[i], f[i], v[i]); 55 | } 56 | Array.Sort(act); // sort according to finish time. 57 | return MaxValueJobsUtil(act, n); 58 | } 59 | 60 | private static int MaxValueJobsUtilTD(int[] dp, Job[] arr, int n) 61 | { 62 | // Base case 63 | if (n == 0) 64 | { 65 | return 0; 66 | } 67 | 68 | if (dp[n - 1] != 0) 69 | { 70 | return dp[n - 1]; 71 | } 72 | 73 | // Find Value when current job is included 74 | int incl = arr[n - 1].value; 75 | for (int j = n - 2; j >= 0; j--) 76 | { 77 | if (arr[j].stop <= arr[n - 1].start) 78 | { 79 | incl += MaxValueJobsUtilTD(dp, arr, j + 1); 80 | break; 81 | } 82 | } 83 | 84 | // Find Value when current job is excluded 85 | int excl = MaxValueJobsUtilTD(dp, arr, n - 1); 86 | dp[n - 1] = Math.Max(incl, excl); 87 | return dp[n - 1]; 88 | } 89 | 90 | 91 | public static int MaxValueJobsTD(int[] s, int[] f, int[] v, int n) 92 | { 93 | Job[] act = new Job[n]; 94 | for (int i = 0;i < n;i++) 95 | { 96 | act[i] = new Job(s[i], f[i], v[i]); 97 | } 98 | Array.Sort(act); // sort according to finish time. 99 | int[] dp = new int[n]; 100 | return MaxValueJobsUtilTD(dp, act, n); 101 | } 102 | 103 | public static int MaxValueJobsBU(int[] s, int[] f, int[] v, int n) 104 | { 105 | Job[] act = new Job[n]; 106 | for (int i = 0;i < n;i++) 107 | { 108 | act[i] = new Job(s[i], f[i], v[i]); 109 | } 110 | Array.Sort(act); // sort according to finish time. 111 | 112 | int[] dp = new int[n]; 113 | dp[0] = act[0].value; 114 | 115 | for (int i = 1; i < n; i++) 116 | { 117 | int incl = act[i].value; 118 | for (int j = i - 1; j >= 0; j--) 119 | { 120 | if (act[j].stop <= act[i].start) 121 | { 122 | incl += dp[j]; 123 | break; 124 | } 125 | } 126 | dp[i] = Math.Max(incl, dp[i - 1]); 127 | } 128 | return dp[n - 1]; 129 | } 130 | 131 | // Testing code. 132 | public static void Main(string[] args) 133 | { 134 | int[] start = new int[] {1, 5, 0, 3, 5, 6, 8}; 135 | int[] finish = new int[] {2, 6, 5, 4, 9, 7, 9}; 136 | int[] value = new int[] {2, 2, 4, 3, 10, 2, 8}; 137 | int n = start.Length; 138 | Console.WriteLine(MaxValueJobs(start, finish, value, n)); 139 | Console.WriteLine(MaxValueJobsTD(start, finish, value, n)); 140 | Console.WriteLine(MaxValueJobsBU(start, finish, value, n)); 141 | } 142 | } 143 | 144 | /* 145 | 17 146 | 17 147 | 17 148 | */ -------------------------------------------------------------------------------- /HashTable/HashTableLP.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class HashTableLP 4 | { 5 | private static int EMPTY_VALUE = -1; 6 | private static int DELETED_VALUE = -2; 7 | private static int FILLED_VALUE = 0; 8 | 9 | private int tableSize; 10 | private int[] key; 11 | private int[] value; 12 | private int[] flag; 13 | 14 | public HashTableLP(int tSize) 15 | { 16 | tableSize = tSize; 17 | key = new int[tSize + 1]; 18 | value = new int[tSize + 1]; 19 | flag = new int[tSize + 1]; 20 | Array.Fill(flag, EMPTY_VALUE); 21 | } 22 | 23 | /* Other Methods */ 24 | 25 | private int ComputeHash(int key) 26 | { 27 | return key % tableSize; 28 | } 29 | 30 | private int ResolverFun(int index) 31 | { 32 | return index; 33 | } 34 | 35 | private int ResolverFun2(int index) 36 | { 37 | return index * index; 38 | } 39 | 40 | public bool Add(int ky, int val) 41 | { 42 | int hashValue = ComputeHash(ky); 43 | for (int i = 0; i < tableSize; i++) 44 | { 45 | if (flag[hashValue] == EMPTY_VALUE || flag[hashValue] == DELETED_VALUE) 46 | { 47 | key[hashValue] = ky; 48 | value[hashValue] = val; 49 | flag[hashValue] = FILLED_VALUE; 50 | return true; 51 | } 52 | hashValue += ResolverFun(i); 53 | hashValue %= tableSize; 54 | } 55 | return false; 56 | } 57 | 58 | public bool Add(int val) 59 | { 60 | return Add(val, val); 61 | } 62 | 63 | public bool Find(int ky) 64 | { 65 | int hashValue = ComputeHash(ky); 66 | for (int i = 0; i < tableSize; i++) 67 | { 68 | if (flag[hashValue] == EMPTY_VALUE) 69 | { 70 | return false; 71 | } 72 | 73 | if (flag[hashValue] == FILLED_VALUE && key[hashValue] == ky) 74 | { 75 | return true; 76 | } 77 | 78 | hashValue += ResolverFun(i); 79 | hashValue %= tableSize; 80 | } 81 | return false; 82 | } 83 | 84 | 85 | public int Get(int ky) 86 | { 87 | int hashValue = ComputeHash(ky); 88 | for (int i = 0; i < tableSize; i++) 89 | { 90 | if (flag[hashValue] == EMPTY_VALUE) 91 | { 92 | return -1; 93 | } 94 | 95 | if (flag[hashValue] == FILLED_VALUE && key[hashValue] == ky) 96 | { 97 | return value[hashValue]; ; 98 | } 99 | 100 | hashValue += ResolverFun(i); 101 | hashValue %= tableSize; 102 | } 103 | return -1; 104 | } 105 | 106 | public bool Remove(int ky) 107 | { 108 | int hashValue = ComputeHash(ky); 109 | for (int i = 0; i < tableSize; i++) 110 | { 111 | if (flag[hashValue] == EMPTY_VALUE) 112 | { 113 | return false; 114 | } 115 | 116 | if (flag[hashValue] == FILLED_VALUE && key[hashValue] == ky) 117 | { 118 | flag[hashValue] = DELETED_VALUE; 119 | return true; 120 | } 121 | hashValue += ResolverFun(i); 122 | hashValue %= tableSize; 123 | } 124 | return false; 125 | } 126 | 127 | public void Print() 128 | { 129 | Console.Write("Hash Table contains :: "); 130 | for (int i = 0; i < tableSize; i++) 131 | { 132 | if (flag[i] == FILLED_VALUE) 133 | { 134 | Console.Write("(" + key[i] + "=>" + value[i] + ") "); 135 | } 136 | } 137 | Console.WriteLine(); 138 | } 139 | 140 | 141 | // Testing code. 142 | public static void Main(string[] args) 143 | { 144 | HashTableLP ht = new HashTableLP(1000); 145 | ht.Add(1, 10); 146 | ht.Add(2, 20); 147 | ht.Add(3, 30); 148 | ht.Print(); 149 | Console.WriteLine("Find key 2 : " + ht.Find(2)); 150 | Console.WriteLine("Value at key 2 : " + ht.Get(2)); 151 | ht.Remove(2); 152 | ht.Print(); 153 | Console.WriteLine("Find key 2 : " + ht.Find(2)); 154 | } 155 | } 156 | 157 | /* 158 | Hash Table contains :: (1=>10) (2=>20) (3=>30) 159 | Find key 2 : True 160 | Value at key 2 : 20 161 | Hash Table contains :: (1=>10) (3=>30) 162 | Find key 2 : False 163 | */ -------------------------------------------------------------------------------- /String/StringMatching.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class StringMatching 4 | { 5 | public static int BruteForceSearch(string text, string pattern) 6 | { 7 | int i = 0, j = 0; 8 | int n = text.Length; 9 | int m = pattern.Length; 10 | while (i <= n - m) 11 | { 12 | j = 0; 13 | while (j < m && pattern[j] == text[i + j]) 14 | { 15 | j++; 16 | } 17 | if (j == m) 18 | { 19 | return (i); 20 | } 21 | i++; 22 | } 23 | return -1; 24 | } 25 | 26 | public static int RobinKarp(string text, string pattern) 27 | { 28 | int n = text.Length; 29 | int m = pattern.Length; 30 | int i, j; 31 | int prime = 101; 32 | int powm = 1; 33 | int TextHash = 0, PatternHash = 0; 34 | if (m == 0 || m > n) 35 | { 36 | return -1; 37 | } 38 | 39 | for (i = 0; i < m - 1; i++) 40 | { 41 | powm = (powm << 1) % prime; 42 | } 43 | 44 | for (i = 0; i < m; i++) 45 | { 46 | PatternHash = ((PatternHash << 1) + pattern[i]) % prime; 47 | TextHash = ((TextHash << 1) + text[i]) % prime; 48 | } 49 | 50 | for (i = 0; i <= (n - m); i++) 51 | { 52 | if (TextHash == PatternHash) 53 | { 54 | for (j = 0; j < m; j++) 55 | { 56 | if (text[i + j] != pattern[j]) 57 | { 58 | break; 59 | } 60 | } 61 | if (j == m) 62 | { 63 | return i; 64 | } 65 | } 66 | TextHash = (((TextHash - text[i] * powm) << 1) + text[i + m]) % prime; 67 | if (TextHash < 0) 68 | { 69 | TextHash = (TextHash + prime); 70 | } 71 | } 72 | return -1; 73 | } 74 | 75 | public static void KMPPreprocess(string pattern, int[] ShiftArr) 76 | { 77 | int m = pattern.Length; 78 | int i = 0, j = -1; 79 | ShiftArr[i] = -1; 80 | while (i < m) 81 | { 82 | while (j >= 0 && pattern[i] != pattern[j]) 83 | { 84 | j = ShiftArr[j]; 85 | } 86 | i++; 87 | j++; 88 | ShiftArr[i] = j; 89 | } 90 | } 91 | 92 | public static int KMP(string text, string pattern) 93 | { 94 | int i = 0, j = 0; 95 | int n = text.Length; 96 | int m = pattern.Length; 97 | int[] ShiftArr = new int[m + 1]; 98 | KMPPreprocess(pattern, ShiftArr); 99 | while (i < n) 100 | { 101 | while (j >= 0 && text[i] != pattern[j]) 102 | { 103 | j = ShiftArr[j]; 104 | } 105 | i++; 106 | j++; 107 | if (j == m) 108 | { 109 | return (i - m); 110 | } 111 | } 112 | return -1; 113 | } 114 | 115 | public static int KMPFindCount(string text, string pattern) 116 | { 117 | int i = 0, j = 0, count = 0; 118 | int n = text.Length; 119 | int m = pattern.Length; 120 | int[] ShiftArr = new int[m + 1]; 121 | KMPPreprocess(pattern, ShiftArr); 122 | while (i < n) 123 | { 124 | while (j >= 0 && text[i] != pattern[j]) 125 | { 126 | j = ShiftArr[j]; 127 | } 128 | i++; 129 | j++; 130 | if (j == m) 131 | { 132 | count++; 133 | j = ShiftArr[j]; 134 | } 135 | } 136 | return count; 137 | } 138 | 139 | // Testing code. 140 | public static void Main(string[] args) 141 | { 142 | string st1 = "hello, world!"; 143 | string st2 = "world"; 144 | Console.WriteLine("BruteForceSearch return : " + BruteForceSearch(st1, st2)); 145 | Console.WriteLine("RobinKarp return : " + RobinKarp(st1, st2)); 146 | Console.WriteLine("KMP return : " + KMP(st1, st2)); 147 | 148 | string str3 = "Only time will tell if we stand the test of time"; 149 | Console.WriteLine("Frequency of 'time' is: " + KMPFindCount(str3, "time")); 150 | } 151 | /* 152 | BruteForceSearch return : 7 153 | RobinKarp return : 7 154 | KMP return : 7 155 | Frequency of 'time' is: 2 156 | */ 157 | } -------------------------------------------------------------------------------- /Tree/SegmentTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class SegmentTree 4 | { 5 | private int[] segArr; 6 | private int size; 7 | 8 | public SegmentTree(int[] input) 9 | { 10 | size = input.Length; 11 | // Height of segment tree. 12 | int x = (int)(Math.Ceiling(Math.Log(size) / Math.Log(2))); 13 | //Maximum size of segment tree 14 | int max_size = 2 * (int) Math.Pow(2, x) - 1; 15 | // Allocate memory for segment tree 16 | segArr = new int[max_size]; 17 | ConstructST(input, 0, size - 1, 0); 18 | } 19 | 20 | 21 | private int ConstructST(int[] input, int start, int end, int index) 22 | { 23 | // Store it in current node of the segment tree and return 24 | if (start == end) 25 | { 26 | segArr[index] = input[start]; 27 | return input[start]; 28 | } 29 | 30 | // If there are more than one elements, 31 | // then traverse left and right subtrees 32 | // and store the sum of values in current node. 33 | int mid = (start + end) / 2; 34 | segArr[index] = ConstructST(input, start, mid, index * 2 + 1) + ConstructST(input, mid + 1, end, index * 2 + 2); 35 | return segArr[index]; 36 | } 37 | 38 | public int GetSum(int start, int end) 39 | { 40 | // Check for error conditions. 41 | if (start > end || start < 0 || end > size - 1) 42 | { 43 | Console.WriteLine("Invalid Input."); 44 | return -1; 45 | } 46 | return GetSumUtil(0, size - 1, start, end, 0); 47 | } 48 | 49 | private int GetSumUtil(int segStart, int segEnd, int queryStart, int queryEnd, int index) 50 | { 51 | if (queryStart <= segStart && segEnd <= queryEnd) // complete overlapping case. 52 | { 53 | return segArr[index]; 54 | } 55 | 56 | if (segEnd < queryStart || queryEnd < segStart) // no overlapping case. 57 | { 58 | return 0; 59 | } 60 | 61 | // Segment tree is partly overlaps with the query range. 62 | int mid = (segStart + segEnd) / 2; 63 | return GetSumUtil(segStart, mid, queryStart, queryEnd, 2 * index + 1) + GetSumUtil(mid + 1, segEnd, queryStart, queryEnd, 2 * index + 2); 64 | } 65 | 66 | public void Set(int[] arr, int ind, int val) 67 | { 68 | // Check for error conditions. 69 | if (ind < 0 || ind > size - 1) 70 | { 71 | Console.WriteLine("Invalid Input."); 72 | return; 73 | } 74 | 75 | arr[ind] = val; 76 | 77 | // Set new value in segment tree 78 | SetUtil(0, size - 1, ind, val, 0); 79 | } 80 | 81 | // Always diff will be returned. 82 | private int SetUtil(int segStart, int segEnd, int ind, int val, int index) 83 | { 84 | // set index lies outside the range of current segment. 85 | // So diff to its parent node will be zero. 86 | if (ind < segStart || ind > segEnd) 87 | { 88 | return 0; 89 | } 90 | 91 | // If the input index is in range of this node, then set the 92 | // value of the node and its children 93 | int diff = 0; 94 | if (segStart == segEnd) 95 | { 96 | if (segStart == ind) 97 | { // Index that need to be set. 98 | diff = val - segArr[index]; 99 | segArr[index] = val; 100 | return diff; 101 | } 102 | else 103 | { 104 | return 0; 105 | } 106 | } 107 | 108 | int mid = (segStart + segEnd) / 2; 109 | diff = SetUtil(segStart, mid, ind, val, 2 * index + 1) + SetUtil(mid + 1, segEnd, ind, val, 2 * index + 2); 110 | 111 | // Current node value is set with diff. 112 | segArr[index] = segArr[index] + diff; 113 | 114 | // Value of diff is propagated to the parent node. 115 | return diff; 116 | } 117 | 118 | // Testing code. 119 | public static void Main(string[] args) 120 | { 121 | int[] arr = new int[] {1, 2, 4, 8, 16, 32, 64}; 122 | SegmentTree tree = new SegmentTree(arr); 123 | Console.WriteLine("Sum of values in the range(0, 3): " + tree.GetSum(1, 3)); 124 | Console.WriteLine("Sum of values of all the elements: " + tree.GetSum(0, arr.Length - 1)); 125 | 126 | tree.Set(arr, 1, 10); 127 | Console.WriteLine("Sum of values in the range(0, 3): " + tree.GetSum(1, 3)); 128 | Console.WriteLine("Sum of values of all the elements: " + tree.GetSum(0, arr.Length - 1)); 129 | } 130 | } 131 | 132 | /* 133 | Sum of values in the range(0, 3): 14 134 | Sum of values of all the elements: 127 135 | Sum of values in the range(0, 3): 22 136 | Sum of values of all the elements: 135 137 | */ -------------------------------------------------------------------------------- /Tree/RangeMaxST.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class RangeMaxST 4 | { 5 | private int[] segArr; 6 | private int n; 7 | 8 | public RangeMaxST(int[] input) 9 | { 10 | n = input.Length; 11 | // Height of segment tree. 12 | int x = (int)(Math.Ceiling(Math.Log(n) / Math.Log(2))); 13 | //Maximum size of segment tree 14 | int max_size = 2 * (int)Math.Pow(2, x) - 1; 15 | // Allocate memory for segment tree 16 | segArr = new int[max_size]; 17 | ConstructST(input, 0, n - 1, 0); 18 | } 19 | 20 | 21 | private int ConstructST(int[] input, int start, int end, int index) 22 | { 23 | // Store it in current node of the segment tree and return 24 | if (start == end) 25 | { 26 | segArr[index] = input[start]; 27 | return input[start]; 28 | } 29 | 30 | // If there are more than one elements, 31 | // then traverse left and right subtrees 32 | // and store the minimum of values in current node. 33 | int mid = (start + end) / 2; 34 | segArr[index] = Math.Max(ConstructST(input, start, mid, index * 2 + 1), ConstructST(input, mid + 1, end, index * 2 + 2)); 35 | return segArr[index]; 36 | } 37 | 38 | public int GetMax(int start, int end) 39 | { 40 | // Check for error conditions. 41 | if (start > end || start < 0 || end > n - 1) 42 | { 43 | Console.WriteLine("Invalid Input."); 44 | return int.MinValue; 45 | } 46 | return GetMaxUtil(0, n - 1, start, end, 0); 47 | } 48 | 49 | private int GetMaxUtil(int segStart, int segEnd, int queryStart, int queryEnd, int index) 50 | { 51 | if (queryStart <= segStart && segEnd <= queryEnd) // complete overlapping case. 52 | { 53 | return segArr[index]; 54 | } 55 | 56 | if (segEnd < queryStart || queryEnd < segStart) // no overlapping case. 57 | { 58 | return int.MinValue; 59 | } 60 | 61 | // Segment tree is partly overlaps with the query range. 62 | int mid = (segStart + segEnd) / 2; 63 | return Math.Max(GetMaxUtil(segStart, mid, queryStart, queryEnd, 2 * index + 1), 64 | GetMaxUtil(mid + 1, segEnd, queryStart, queryEnd, 2 * index + 2)); 65 | } 66 | 67 | public void Update(int ind, int val) 68 | { 69 | // Check for error conditions. 70 | if (ind < 0 || ind > n - 1) 71 | { 72 | Console.WriteLine("Invalid Input."); 73 | return; 74 | } 75 | 76 | // Update the values in segment tree 77 | UpdateUtil(0, n - 1, ind, val, 0); 78 | } 79 | 80 | // Always min inside valid range will be returned. 81 | private int UpdateUtil(int segStart, int segEnd, int ind, int val, int index) 82 | { 83 | // Update index lies outside the range of current segment. 84 | // So minimum will not change. 85 | if (ind < segStart || ind > segEnd) 86 | { 87 | return segArr[index]; 88 | } 89 | 90 | // If the input index is in range of this node, then update the 91 | // value of the node and its children 92 | 93 | if (segStart == segEnd) 94 | { 95 | if (segStart == ind) 96 | { // Index value need to be updated. 97 | segArr[index] = val; 98 | return val; 99 | } 100 | else 101 | { 102 | return segArr[index]; // index value is not changed. 103 | } 104 | } 105 | 106 | int mid = (segStart + segEnd) / 2; 107 | 108 | // Current node value is updated with min. 109 | segArr[index] = Math.Max(UpdateUtil(segStart, mid, ind, val, 2 * index + 1), UpdateUtil(mid + 1, segEnd, ind, val, 2 * index + 2)); 110 | 111 | // Value of diff is propagated to the parent node. 112 | return segArr[index]; 113 | } 114 | 115 | // Testing code. 116 | public static void Main(string[] args) 117 | { 118 | int[] arr = new int[] { 1, 8, 2, 7, 3, 6, 4, 5 }; 119 | RangeMaxST tree = new RangeMaxST(arr); 120 | Console.WriteLine("Max value in the range(1, 5): " + tree.GetMax(1, 5)); 121 | Console.WriteLine("Max value in the range(2, 7): " + tree.GetMax(2, 7)); 122 | Console.WriteLine("Max value of all the elements: " + tree.GetMax(0, arr.Length - 1)); 123 | 124 | tree.Update(2, 9); 125 | Console.WriteLine("Max value in the range(1, 5): " + tree.GetMax(1, 5)); 126 | Console.WriteLine("Max value of all the elements: " + tree.GetMax(0, arr.Length - 1)); 127 | } 128 | } 129 | 130 | /* 131 | Max value in the range(1, 5): 8 132 | Max value in the range(2, 7): 7 133 | Max value of all the elements: 8 134 | Max value in the range(1, 5): 9 135 | Max value of all the elements: 9 136 | */ 137 | -------------------------------------------------------------------------------- /Introduction/Introduction.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | public class Introduction 5 | { 6 | public static void PrintArray(int[] arr, int count) 7 | { 8 | Console.Write("["); 9 | for (int i = 0; i < count; i++) 10 | { 11 | Console.Write(" " + arr[i]); 12 | } 13 | Console.WriteLine(" ]"); 14 | } 15 | 16 | public static void Swap(int[] arr, int x, int y) 17 | { 18 | int temp = arr[x]; 19 | arr[x] = arr[y]; 20 | arr[y] = temp; 21 | return; 22 | } 23 | 24 | public static int Factorial(int i) 25 | { 26 | // Termination Condition 27 | if (i <= 1) 28 | { 29 | return 1; 30 | } 31 | // Body, Recursive Expansion 32 | return i * Factorial(i - 1); 33 | } 34 | 35 | /* Testing code */ 36 | public static void Main14() 37 | { 38 | Console.WriteLine("Factorial:" + Factorial(5)); 39 | } 40 | // Factorial:120 41 | 42 | public static void PrintInt10(int number) 43 | { 44 | char digit = (char)(number % 10 + '0'); 45 | number = number / 10; 46 | if (number != 0) 47 | { 48 | PrintInt10(number); 49 | } 50 | Console.Write(digit); 51 | } 52 | 53 | public static void PrintInt(int number, int outputbase) 54 | { 55 | string conversion = "0123456789ABCDEF"; 56 | char digit = (char)(number % outputbase); 57 | number = number / outputbase; 58 | if (number != 0) 59 | { 60 | PrintInt(number, outputbase); 61 | } 62 | Console.Write(conversion[digit]); 63 | } 64 | 65 | /* Testing code */ 66 | public static void Main15() 67 | { 68 | PrintInt(500, 16); 69 | Console.WriteLine(); 70 | } 71 | 72 | /* 73 | 1F4 74 | */ 75 | 76 | 77 | public static void TowerOfHanoi(int num, char src, char dst, char temp) 78 | { 79 | if (num < 1) 80 | { 81 | return; 82 | } 83 | 84 | TowerOfHanoi(num - 1, src, temp, dst); 85 | Console.WriteLine("Move " + num + " disk from peg " + src + " to peg " + dst); 86 | TowerOfHanoi(num - 1, temp, dst, src); 87 | } 88 | 89 | /* Testing code */ 90 | public static void Main16() 91 | { 92 | int num = 3; 93 | Console.WriteLine("Moves involved in the Tower of Hanoi are:"); 94 | TowerOfHanoi(num, 'A', 'C', 'B'); 95 | } 96 | 97 | /* 98 | Moves involved in the Tower of Hanoi are: 99 | Move 1 disk from peg A to peg C 100 | Move 2 disk from peg A to peg B 101 | Move 1 disk from peg C to peg B 102 | Move 3 disk from peg A to peg C 103 | Move 1 disk from peg B to peg A 104 | Move 2 disk from peg B to peg C 105 | Move 1 disk from peg A to peg C 106 | */ 107 | 108 | public static int Gcd(int m, int n) 109 | { 110 | if (n == 0) 111 | return m; 112 | 113 | if (m == 0) 114 | return n; 115 | 116 | return (Gcd(n, m % n)); 117 | } 118 | 119 | /* Testing code */ 120 | public static void Main17() 121 | { 122 | Console.WriteLine("Gcd is:: " + Gcd(5, 2)); 123 | } 124 | 125 | /* 126 | Gcd is:: 1 127 | */ 128 | 129 | public static int Fibonacci(int n) 130 | { 131 | if (n < 2) 132 | { 133 | return n; 134 | } 135 | return Fibonacci(n - 1) + Fibonacci(n - 2); 136 | } 137 | 138 | /* Testing code */ 139 | public static void Main18() 140 | { 141 | Console.WriteLine(Fibonacci(10) + " "); 142 | } 143 | 144 | /* 145 | 55 146 | */ 147 | 148 | public static void Permutation(int[] arr, int i, int length) 149 | { 150 | if (length == i) 151 | { 152 | PrintArray(arr, length); 153 | return; 154 | } 155 | int j = i; 156 | for (j = i; j < length; j++) 157 | { 158 | Swap(arr, i, j); 159 | Permutation(arr, i + 1, length); 160 | Swap(arr, i, j); 161 | } 162 | return; 163 | } 164 | 165 | /* Testing code */ 166 | public static void Main19() 167 | { 168 | int[] arr = new int[3]; 169 | for (int i = 0; i < 3; i++) 170 | { 171 | arr[i] = i; 172 | } 173 | Permutation(arr, 0, 3); 174 | } 175 | /* 176 | [ 0 1 2 ] 177 | [ 0 2 1 ] 178 | [ 1 0 2 ] 179 | [ 1 2 0 ] 180 | [ 2 1 0 ] 181 | [ 2 0 1 ] 182 | */ 183 | 184 | public static void Main(string[] args) 185 | { 186 | Main1(); 187 | Introduction i = new Introduction(); 188 | i.Main2(); 189 | Main3(); 190 | Main4(); 191 | Main5(); 192 | Main6(); 193 | Main7(); 194 | Main8(); 195 | Main9(); 196 | Main10(); 197 | Main11(); 198 | Main12(); 199 | Main13(); 200 | Main14(); 201 | Main15(); 202 | Main16(); 203 | Main17(); 204 | Main18(); 205 | Main19(); 206 | Main20(); 207 | } 208 | } 209 | 210 | -------------------------------------------------------------------------------- /AlgorithmsChapters/Greedy/OptimalMergePattern.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class OptimalMergePattern 4 | { 5 | public static int Merge(int[] lists, int size) 6 | { 7 | PriorityQueue pq = new PriorityQueue(); 8 | int i = 0; 9 | for (i = 0; i < size; i++) 10 | { 11 | pq.Enqueue(lists[i]); 12 | } 13 | 14 | int total = 0; 15 | int value = 0; 16 | while (pq.Size() > 1) 17 | { 18 | value = pq.Dequeue(); 19 | value += pq.Dequeue(); 20 | pq.Enqueue(value); 21 | total += value; 22 | } 23 | Console.WriteLine("Total : " + total); 24 | return total; 25 | } 26 | 27 | // Testing code. 28 | public static void Main(string[] args) 29 | { 30 | int[] lists = new int[] {4, 3, 2, 6}; 31 | OptimalMergePattern.Merge(lists, lists.Length); 32 | } 33 | } 34 | 35 | 36 | /* 37 | Total : 29 38 | */ 39 | 40 | public class PriorityQueue where T : IComparable 41 | { 42 | private int CAPACITY = 32; 43 | private int count; // Number of elements in Heap 44 | private T[] arr; // The Heap array 45 | private bool isMinHeap; 46 | 47 | public PriorityQueue(bool isMin = true) 48 | { 49 | arr = new T[CAPACITY]; 50 | count = 0; 51 | isMinHeap = isMin; 52 | } 53 | 54 | public PriorityQueue(T[] array, bool isMin = true) 55 | { 56 | CAPACITY = count = array.Length; 57 | arr = array; 58 | isMinHeap = isMin; 59 | // Build Heap operation over array 60 | for (int i = (count / 2); i >= 0; i--) 61 | { 62 | PercolateDown(i); 63 | } 64 | } 65 | 66 | // Other Methods. 67 | private bool Compare(T[] arr, int first, int second) 68 | { 69 | if (isMinHeap) 70 | return arr[first].CompareTo(arr[second]) > 0; 71 | else 72 | return arr[first].CompareTo(arr[second]) < 0; 73 | } 74 | 75 | private void PercolateDown(int parent) 76 | { 77 | int lChild = 2 * parent + 1; 78 | int rChild = lChild + 1; 79 | int child = -1; 80 | T temp; 81 | 82 | if (lChild < count) 83 | { 84 | child = lChild; 85 | } 86 | 87 | if (rChild < count && Compare(arr, lChild, rChild)) 88 | { 89 | child = rChild; 90 | } 91 | 92 | if (child != -1 && Compare(arr, parent, child)) 93 | { 94 | temp = arr[parent]; 95 | arr[parent] = arr[child]; 96 | arr[child] = temp; 97 | PercolateDown(child); 98 | } 99 | } 100 | 101 | private void PercolateUp(int child) 102 | { 103 | int parent = (child - 1) / 2; 104 | T temp; 105 | if (parent < 0) 106 | { 107 | return; 108 | } 109 | 110 | if (Compare(arr, parent, child)) 111 | { 112 | temp = arr[child]; 113 | arr[child] = arr[parent]; 114 | arr[parent] = temp; 115 | PercolateUp(parent); 116 | } 117 | } 118 | 119 | public void Enqueue(T value) 120 | { 121 | if (count == CAPACITY) 122 | { 123 | DoubleSize(); 124 | } 125 | 126 | arr[count++] = value; 127 | PercolateUp(count - 1); 128 | } 129 | 130 | private void DoubleSize() 131 | { 132 | T[] old = arr; 133 | arr = new T[arr.Length * 2]; 134 | CAPACITY *= 2; 135 | Array.Copy(old, 0, arr, 0, count); 136 | } 137 | 138 | public T Dequeue() 139 | { 140 | if (count == 0) 141 | { 142 | throw new System.InvalidOperationException(); 143 | } 144 | 145 | T value = arr[0]; 146 | arr[0] = arr[count - 1]; 147 | count--; 148 | PercolateDown(0); 149 | return value; 150 | } 151 | 152 | public void Print() 153 | { 154 | for (int i = 0; i < count; i++) 155 | { 156 | Console.Write(arr[i] + " "); 157 | } 158 | Console.WriteLine(); 159 | } 160 | 161 | public bool IsEmpty() 162 | { 163 | return (count == 0); 164 | } 165 | 166 | public int Size() 167 | { 168 | return count; 169 | } 170 | 171 | public T Peek() 172 | { 173 | if (count == 0) 174 | { 175 | throw new System.InvalidOperationException(); 176 | } 177 | return arr[0]; 178 | } 179 | 180 | public static void HeapSort(int[] array, bool inc) 181 | { 182 | // Create max heap for increasing order sorting. 183 | PriorityQueue hp = new PriorityQueue(array, !inc); 184 | for (int i = 0; i < array.Length; i++) 185 | { 186 | array[array.Length - i - 1] = hp.Dequeue(); 187 | } 188 | } 189 | } 190 | -------------------------------------------------------------------------------- /AlgorithmsChapters/Greedy/PriorityQueue.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class PriorityQueueDemo 4 | { 5 | public static void Main(string[] args) 6 | { 7 | 8 | PriorityQueue pq = new PriorityQueue(); 9 | int[] arr = new int[] {1, 2, 10, 8, 7, 3, 4, 6, 5, 9}; 10 | foreach (int i in arr) 11 | { 12 | pq.Enqueue(i); 13 | } 14 | 15 | Console.Write("Heap Array: "); 16 | pq.Print(); 17 | while (pq.IsEmpty() == false) 18 | { 19 | Console.Write(pq.Dequeue() + " "); 20 | } 21 | Console.WriteLine(); 22 | 23 | pq = new PriorityQueue(false); 24 | foreach (int i in arr) 25 | { 26 | pq.Enqueue(i); 27 | } 28 | 29 | Console.Write("Heap Array: "); 30 | pq.Print(); 31 | while (pq.IsEmpty() == false) 32 | { 33 | Console.Write(pq.Dequeue() + " "); 34 | } 35 | } 36 | } 37 | 38 | public class PriorityQueue where T : IComparable 39 | { 40 | private int CAPACITY = 32; 41 | private int count; // Number of elements in Heap 42 | private T[] arr; // The Heap array 43 | private bool isMinHeap; 44 | 45 | public PriorityQueue(bool isMin = true) 46 | { 47 | arr = new T[CAPACITY]; 48 | count = 0; 49 | isMinHeap = isMin; 50 | } 51 | 52 | public PriorityQueue(T[] array, bool isMin = true) 53 | { 54 | CAPACITY = count = array.Length; 55 | arr = array; 56 | isMinHeap = isMin; 57 | // Build Heap operation over array 58 | for (int i = (count / 2); i >= 0; i--) 59 | { 60 | PercolateDown(i); 61 | } 62 | } 63 | 64 | // Other Methods. 65 | private bool Compare(T[] arr, int first, int second) 66 | { 67 | if (isMinHeap) 68 | return arr[first].CompareTo(arr[second]) > 0; 69 | else 70 | return arr[first].CompareTo(arr[second]) < 0; 71 | } 72 | 73 | private void PercolateDown(int parent) 74 | { 75 | int lChild = 2 * parent + 1; 76 | int rChild = lChild + 1; 77 | int child = -1; 78 | T temp; 79 | 80 | if (lChild < count) 81 | { 82 | child = lChild; 83 | } 84 | 85 | if (rChild < count && Compare(arr, lChild, rChild)) 86 | { 87 | child = rChild; 88 | } 89 | 90 | if (child != -1 && Compare(arr, parent, child)) 91 | { 92 | temp = arr[parent]; 93 | arr[parent] = arr[child]; 94 | arr[child] = temp; 95 | PercolateDown(child); 96 | } 97 | } 98 | 99 | private void PercolateUp(int child) 100 | { 101 | int parent = (child - 1) / 2; 102 | T temp; 103 | if (parent < 0) 104 | { 105 | return; 106 | } 107 | 108 | if (Compare(arr, parent, child)) 109 | { 110 | temp = arr[child]; 111 | arr[child] = arr[parent]; 112 | arr[parent] = temp; 113 | PercolateUp(parent); 114 | } 115 | } 116 | 117 | public void Enqueue(T value) 118 | { 119 | if (count == CAPACITY) 120 | { 121 | DoubleSize(); 122 | } 123 | 124 | arr[count++] = value; 125 | PercolateUp(count - 1); 126 | } 127 | 128 | private void DoubleSize() 129 | { 130 | T[] old = arr; 131 | arr = new T[arr.Length * 2]; 132 | CAPACITY *= 2; 133 | Array.Copy(old, 0, arr, 0, count); 134 | } 135 | 136 | public T Dequeue() 137 | { 138 | if (count == 0) 139 | { 140 | throw new System.InvalidOperationException(); 141 | } 142 | 143 | T value = arr[0]; 144 | arr[0] = arr[count - 1]; 145 | count--; 146 | PercolateDown(0); 147 | return value; 148 | } 149 | 150 | public void Print() 151 | { 152 | for (int i = 0; i < count; i++) 153 | { 154 | Console.Write(arr[i] + " "); 155 | } 156 | Console.WriteLine(); 157 | } 158 | 159 | public bool IsEmpty() 160 | { 161 | return (count == 0); 162 | } 163 | 164 | public int Size() 165 | { 166 | return count; 167 | } 168 | 169 | public T Peek() 170 | { 171 | if (count == 0) 172 | { 173 | throw new System.InvalidOperationException(); 174 | } 175 | return arr[0]; 176 | } 177 | 178 | public static void HeapSort(int[] array, bool inc) 179 | { 180 | // Create max heap for increasing order sorting. 181 | PriorityQueue hp = new PriorityQueue(array, !inc); 182 | for (int i = 0; i < array.Length; i++) 183 | { 184 | array[array.Length - i - 1] = hp.Dequeue(); 185 | } 186 | } 187 | } 188 | 189 | -------------------------------------------------------------------------------- /HashTable/HashTableExercise.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | public class HashTableExercise 5 | { 6 | public static bool IsAnagram(char[] str1, char[] str2) 7 | { 8 | int size1 = str1.Length; 9 | int size2 = str2.Length; 10 | if (size1 != size2) 11 | { 12 | return false; 13 | } 14 | 15 | Dictionary hm = new Dictionary(); 16 | foreach (char ch in str1) 17 | { 18 | if (hm.ContainsKey(ch)) 19 | { 20 | hm[ch] = hm[ch] + 1; 21 | } 22 | else 23 | { 24 | hm[ch] = 1; 25 | } 26 | } 27 | 28 | foreach (char ch in str2) 29 | { 30 | if (hm.ContainsKey(ch) == false || hm[ch] == 0) 31 | { 32 | return false; 33 | } 34 | else 35 | { 36 | hm[ch] = hm[ch] - 1; 37 | } 38 | } 39 | return true; 40 | } 41 | 42 | // Testing code. 43 | public static void Main1() 44 | { 45 | char[] first = "hello".ToCharArray(); 46 | char[] second = "elloh".ToCharArray(); 47 | char[] third = "world".ToCharArray(); 48 | 49 | Console.WriteLine("IsAnagram : " + IsAnagram(first, second)); 50 | Console.WriteLine("IsAnagram : " + IsAnagram(first, third)); 51 | } 52 | /* 53 | IsAnagram : True 54 | IsAnagram : False 55 | */ 56 | 57 | public static string RemoveDuplicate(char[] str) 58 | { 59 | HashSet hs = new HashSet(); 60 | string output = ""; 61 | 62 | foreach (char ch in str) 63 | { 64 | if (hs.Contains(ch) == false) 65 | { 66 | output += ch; 67 | hs.Add(ch); 68 | } 69 | } 70 | return output; 71 | } 72 | 73 | // Testing code. 74 | public static void Main2() 75 | { 76 | char[] first = "hello".ToCharArray(); 77 | Console.WriteLine(RemoveDuplicate(first)); 78 | } 79 | 80 | /* 81 | helo 82 | */ 83 | 84 | public static int FindMissing(int[] arr, int start, int end) 85 | { 86 | HashSet hs = new HashSet(); 87 | foreach (int i in arr) 88 | { 89 | hs.Add(i); 90 | } 91 | 92 | for (int curr = start; curr <= end; curr++) 93 | { 94 | if (hs.Contains(curr) == false) 95 | { 96 | return curr; 97 | } 98 | } 99 | return int.MaxValue; 100 | } 101 | 102 | // Testing code. 103 | public static void Main3() 104 | { 105 | int[] arr = new int[] { 1, 2, 3, 5, 6, 7, 8, 9, 10 }; 106 | Console.WriteLine(FindMissing(arr, 1, 10)); 107 | } 108 | /* 109 | 4 110 | */ 111 | 112 | public static void PrintRepeating(int[] arr) 113 | { 114 | HashSet hs = new HashSet(); 115 | 116 | Console.Write("Repeating elements are : "); 117 | foreach (int val in arr) 118 | { 119 | if (hs.Contains(val)) 120 | { 121 | Console.Write(val + " "); 122 | } 123 | else 124 | { 125 | hs.Add(val); 126 | } 127 | } 128 | } 129 | 130 | // Testing code. 131 | public static void Main4() 132 | { 133 | int[] arr1 = new int[] { 1, 2, 3, 4, 4, 5, 6, 7, 8, 9, 1 }; 134 | PrintRepeating(arr1); 135 | } 136 | /* 137 | Repeating elements are : 4 1 138 | */ 139 | 140 | public static void PrintFirstRepeating(int[] arr) 141 | { 142 | int i; 143 | int size = arr.Length; 144 | HashSet hs = new HashSet(); 145 | int firstRepeating = int.MaxValue; 146 | 147 | for (i = size - 1; i >= 0; i--) 148 | { 149 | if (hs.Contains(arr[i])) 150 | { 151 | firstRepeating = arr[i]; 152 | } 153 | hs.Add(arr[i]); 154 | } 155 | Console.WriteLine("First Repeating number is : " + firstRepeating); 156 | } 157 | 158 | // Testing code. 159 | public static void Main5() 160 | { 161 | int[] arr1 = new int[] { 1, 2, 3, 4, 4, 5, 6, 7, 8, 9, 1 }; 162 | PrintFirstRepeating(arr1); 163 | } 164 | /* 165 | First Repeating number is : 1 166 | */ 167 | 168 | public static int HornerHash(char[] key, int tableSize) 169 | { 170 | int size = key.Length; 171 | int h = 0; 172 | int i; 173 | for (i = 0; i < size; i++) 174 | { 175 | h = (32 * h + key[i]) % tableSize; 176 | } 177 | return h; 178 | } 179 | 180 | public static void Main(string[] args) 181 | { 182 | Main1(); 183 | Main2(); 184 | Main3(); 185 | Main4(); 186 | Main5(); 187 | } 188 | 189 | } -------------------------------------------------------------------------------- /AlgorithmsChapters/DP/MatrixCM.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class MatrixCM 4 | { 5 | 6 | private static int MatrixChainMulBruteForce(int[] p, int i, int j) 7 | { 8 | if (i == j) 9 | return 0; 10 | 11 | int min = int.MaxValue; 12 | 13 | // place parenthesis at different places between 14 | // first and last matrix, recursively calculate 15 | // count of multiplications for each parenthesis 16 | // placement and return the minimum count 17 | for (int k = i; k < j; k++) 18 | { 19 | int count = MatrixChainMulBruteForce(p, i, k) + MatrixChainMulBruteForce(p, k + 1, j) + p[i - 1] * p[k] * p[j]; 20 | 21 | if (count < min) 22 | { 23 | min = count; 24 | } 25 | } 26 | 27 | // Return minimum count 28 | return min; 29 | } 30 | 31 | public static int MatrixChainMulBruteForce(int[] p, int n) 32 | { 33 | int i = 1, j = n - 1; 34 | return MatrixChainMulBruteForce(p, i, j); 35 | } 36 | 37 | public static int MatrixChainMulTD(int[] p, int n) 38 | { 39 | int[,] dp = new int[n, n]; 40 | for (int i = 0; i < n; i++) 41 | { 42 | for (int j = 0; j < n; j++) 43 | dp[i, j] = int.MaxValue; 44 | dp[i, i] = 0; 45 | } 46 | return MatrixChainMulTD(dp, p, 1, n - 1); 47 | } 48 | 49 | private static int MatrixChainMulTD(int[,] dp, int[] p, int i, int j) 50 | { 51 | // Base Case 52 | if (dp[i, j] != int.MaxValue) 53 | { 54 | return dp[i, j]; 55 | } 56 | 57 | for (int k = i; k < j; k++) 58 | { 59 | dp[i, j] = Math.Min(dp[i, j], MatrixChainMulTD(dp, p, i, k) + MatrixChainMulTD(dp, p, k + 1, j) + p[i - 1] * p[k] * p[j]); 60 | } 61 | return dp[i, j]; 62 | } 63 | 64 | 65 | 66 | public static int MatrixChainMulBU(int[] p, int n) 67 | { 68 | int[,] dp = new int[n, n]; 69 | for (int i = 0; i < n; i++) 70 | { 71 | for (int j = 0; j < n; j++) 72 | dp[i, j] = int.MaxValue; 73 | dp[i, i] = 0; 74 | } 75 | 76 | for (int l = 1; l < n; l++) // l is length of range. 77 | { 78 | for (int i = 1, j = i + l; j < n; i++, j++) 79 | { 80 | for (int k = i; k < j; k++) 81 | { 82 | dp[i, j] = Math.Min(dp[i, j], dp[i, k] + p[i - 1] * p[k] * p[j] + dp[k + 1, j]); 83 | } 84 | } 85 | } 86 | return dp[1, n - 1]; 87 | } 88 | 89 | static void PrintOptPar(int n, int[,] pos, int i, int j) 90 | { 91 | if (i == j) 92 | Console.Write("M" + pos[i, i] + " "); 93 | 94 | else 95 | { 96 | Console.Write("( "); 97 | PrintOptPar(n, pos, i, pos[i, j]); 98 | PrintOptPar(n, pos, pos[i, j] + 1, j); 99 | Console.Write(") "); 100 | } 101 | } 102 | 103 | static void PrintOptimalParenthesis(int n, int[,] pos) 104 | { 105 | Console.Write("OptimalParenthesis : "); 106 | PrintOptPar(n, pos, 1, n - 1); 107 | Console.WriteLine(); 108 | } 109 | 110 | public static int MatrixChainMulBU2(int[] p, int n) 111 | { 112 | int[,] dp = new int[n, n]; 113 | int[,] pos = new int[n, n]; 114 | 115 | for (int i = 0; i < n; i++) 116 | { 117 | for (int j = 0; j < n; j++) 118 | dp[i, j] = int.MaxValue; 119 | dp[i, i] = 0; 120 | pos[i, i] = i; 121 | } 122 | 123 | for (int l = 1; l < n; l++) // l is length of range. 124 | { 125 | for (int i = 1, j = i + l; j < n; i++, j++) 126 | { 127 | for (int k = i; k < j; k++) 128 | { 129 | dp[i, j] = Math.Min(dp[i, j], dp[i, k] + p[i - 1] * p[k] * p[j] + dp[k + 1, j]); 130 | pos[i, j] = k; 131 | } 132 | } 133 | } 134 | PrintOptimalParenthesis(n, pos); 135 | return dp[1, n - 1]; 136 | } 137 | 138 | 139 | 140 | // Testing code. 141 | public static void Main(string[] args) 142 | { 143 | int[] arr = new int[] { 1, 2, 3, 4 }; 144 | int n = arr.Length; 145 | Console.WriteLine("Matrix Chain Multiplication is: " + MatrixChainMulBruteForce(arr, n)); 146 | Console.WriteLine("Matrix Chain Multiplication is: " + MatrixChainMulTD(arr, n)); 147 | Console.WriteLine("Matrix Chain Multiplication is: " + MatrixChainMulBU(arr, n)); 148 | Console.WriteLine("Matrix Chain Multiplication is: " + MatrixChainMulBU2(arr, n)); 149 | } 150 | } 151 | 152 | /* 153 | Matrix Chain Multiplication is: 18 154 | Matrix Chain Multiplication is: 18 155 | Matrix Chain Multiplication is: 18 156 | OptimalParenthesis : ( ( M1 M2 ) M3 ) 157 | Matrix Chain Multiplication is: 18 158 | */ 159 | 160 | -------------------------------------------------------------------------------- /AlgorithmsChapters/DP/Knapsack.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class Knapsack 4 | { 5 | public static int MaxCost01Knapsack(int[] wt, int[] cost, int capacity) 6 | { 7 | return MaxCost01KnapsackUtil(wt, cost, wt.Length, capacity); 8 | } 9 | 10 | private static int MaxCost01KnapsackUtil(int[] wt, int[] cost, int n, int capacity) 11 | { 12 | // Base Case 13 | if (n == 0 || capacity == 0) 14 | return 0; 15 | 16 | // Return the maximum of two cases: 17 | // (1) nth item is included 18 | // (2) nth item is not included 19 | int first = 0; 20 | if (wt[n - 1] <= capacity) 21 | first = cost[n - 1] + MaxCost01KnapsackUtil(wt, cost, n - 1, capacity - wt[n - 1]); 22 | 23 | int second = MaxCost01KnapsackUtil(wt, cost, n - 1, capacity); 24 | return Math.Max(first, second); 25 | } 26 | 27 | public static int MaxCost01KnapsackTD(int[] wt, int[] cost, int capacity) 28 | { 29 | int n = wt.Length; 30 | int[,] dp = new int[capacity + 1, n + 1]; 31 | return MaxCost01KnapsackTD(dp, wt, cost, n, capacity); 32 | } 33 | 34 | private static int MaxCost01KnapsackTD(int[,] dp, int[] wt, int[] cost, int i, int w) 35 | { 36 | if (w == 0 || i == 0) 37 | return 0; 38 | 39 | if (dp[w, i] != 0) 40 | return dp[w, i]; 41 | 42 | // Their are two cases: 43 | // (1) ith item is included 44 | // (2) ith item is not included 45 | int first = 0; 46 | if (wt[i - 1] <= w) 47 | first = MaxCost01KnapsackTD(dp, wt, cost, i - 1, w - wt[i - 1]) + cost[i - 1]; 48 | 49 | int second = MaxCost01KnapsackTD(dp, wt, cost, i - 1, w); 50 | return dp[w, i] = Math.Max(first, second); 51 | } 52 | 53 | public static int MaxCost01KnapsackBU(int[] wt, int[] cost, int capacity) 54 | { 55 | int n = wt.Length; 56 | int[,] dp = new int[capacity + 1, n + 1]; 57 | 58 | // Build table dp[, ] in bottom up approach. 59 | // Weights considered against capacity. 60 | for (int w = 1; w <= capacity; w++) 61 | { 62 | for (int i = 1; i <= n; i++) 63 | { 64 | // Their are two cases: 65 | // (1) ith item is included 66 | // (2) ith item is not included 67 | int first = 0; 68 | if (wt[i - 1] <= w) 69 | first = dp[w - wt[i - 1], i - 1] + cost[i - 1]; 70 | 71 | int second = dp[w, i - 1]; 72 | dp[w, i] = Math.Max(first, second); 73 | } 74 | } 75 | PrintItems(dp, wt, cost, n, capacity); 76 | return dp[capacity, n]; // Number of weights considered and final capacity. 77 | } 78 | 79 | private static void PrintItems(int[,] dp, int[] wt, int[] cost, int n, int capacity) 80 | { 81 | int totalCost = dp[capacity, n]; 82 | Console.Write("Selected items are:"); 83 | for (int i = n - 1; i > 0; i--) 84 | { 85 | if (totalCost != dp[capacity, i - 1]) 86 | { 87 | Console.Write(" (wt:" + wt[i] + ", cost:" + cost[i] + ")"); 88 | capacity -= wt[i]; 89 | totalCost -= cost[i]; 90 | } 91 | } 92 | Console.WriteLine(); 93 | } 94 | 95 | public static int KS01UnboundBU(int[] wt, int[] cost, int capacity) 96 | { 97 | int n = wt.Length; 98 | int[] dp = new int[capacity + 1]; 99 | 100 | // Build table dp[] in bottom up approach. 101 | // Weights considered against capacity. 102 | for (int w = 1; w <= capacity; w++) 103 | { 104 | for (int i = 1; i <= n; i++) 105 | { 106 | // Their are two cases: 107 | // (1) ith item is included 108 | // (2) ith item is not included 109 | if (wt[i - 1] <= w) 110 | { 111 | dp[w] = Math.Max(dp[w], dp[w - wt[i - 1]] + cost[i - 1]); 112 | } 113 | } 114 | } 115 | //PrintItems(dp, wt, cost, n, capacity); 116 | return dp[capacity]; // Number of weights considered and final capacity. 117 | } 118 | 119 | // Testing code. 120 | public static void Main(string[] args) 121 | { 122 | int[] wt = new int[] { 10, 40, 20, 30 }; 123 | int[] cost = new int[] { 60, 40, 90, 120 }; 124 | int capacity = 50; 125 | 126 | double maxCost = MaxCost01Knapsack(wt, cost, capacity); 127 | Console.WriteLine("Maximum cost obtained = " + maxCost); 128 | maxCost = MaxCost01KnapsackBU(wt, cost, capacity); 129 | Console.WriteLine("Maximum cost obtained = " + maxCost); 130 | maxCost = MaxCost01KnapsackTD(wt, cost, capacity); 131 | Console.WriteLine("Maximum cost obtained = " + maxCost); 132 | } 133 | } 134 | 135 | /* 136 | Maximum cost obtained = 210 137 | Selected items are: (wt:30, cost:120) (wt:20, cost:90) 138 | Maximum cost obtained = 210 139 | Maximum cost obtained = 210 140 | */ -------------------------------------------------------------------------------- /Language and Collections/PriorityQueueDemo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class PriorityQueueDemo 4 | { 5 | public static void Main(string[] args) 6 | { 7 | 8 | PriorityQueue pq = new PriorityQueue(); 9 | int[] arr = new int[] {1, 2, 10, 8, 7, 3, 4, 6, 5, 9}; 10 | foreach (int i in arr) 11 | { 12 | pq.Enqueue(i); 13 | } 14 | 15 | Console.Write("Heap Array: "); 16 | pq.Print(); 17 | while (pq.IsEmpty() == false) 18 | { 19 | Console.Write(pq.Dequeue() + " "); 20 | } 21 | Console.WriteLine(); 22 | 23 | pq = new PriorityQueue(false); 24 | foreach (int i in arr) 25 | { 26 | pq.Enqueue(i); 27 | } 28 | 29 | Console.Write("Heap Array: "); 30 | pq.Print(); 31 | while (pq.IsEmpty() == false) 32 | { 33 | Console.Write(pq.Dequeue() + " "); 34 | } 35 | } 36 | } 37 | 38 | public class PriorityQueue where T : IComparable 39 | { 40 | private int CAPACITY = 32; 41 | private int count; // Number of elements in Heap 42 | private T[] arr; // The Heap array 43 | private bool isMinHeap; 44 | 45 | public PriorityQueue(bool isMin = true) 46 | { 47 | arr = new T[CAPACITY]; 48 | count = 0; 49 | isMinHeap = isMin; 50 | } 51 | 52 | public PriorityQueue(T[] array, bool isMin = true) 53 | { 54 | CAPACITY = count = array.Length; 55 | arr = array; 56 | isMinHeap = isMin; 57 | // Build Heap operation over array 58 | for (int i = (count / 2); i >= 0; i--) 59 | { 60 | PercolateDown(i); 61 | } 62 | } 63 | 64 | // Other Methods. 65 | private bool Compare(T[] arr, int first, int second) 66 | { 67 | if (isMinHeap) 68 | return arr[first].CompareTo(arr[second]) > 0; 69 | else 70 | return arr[first].CompareTo(arr[second]) < 0; 71 | } 72 | 73 | private void PercolateDown(int parent) 74 | { 75 | int lChild = 2 * parent + 1; 76 | int rChild = lChild + 1; 77 | int child = -1; 78 | T temp; 79 | 80 | if (lChild < count) 81 | { 82 | child = lChild; 83 | } 84 | 85 | if (rChild < count && Compare(arr, lChild, rChild)) 86 | { 87 | child = rChild; 88 | } 89 | 90 | if (child != -1 && Compare(arr, parent, child)) 91 | { 92 | temp = arr[parent]; 93 | arr[parent] = arr[child]; 94 | arr[child] = temp; 95 | PercolateDown(child); 96 | } 97 | } 98 | 99 | private void PercolateUp(int child) 100 | { 101 | int parent = (child - 1) / 2; 102 | T temp; 103 | if (parent < 0) 104 | { 105 | return; 106 | } 107 | 108 | if (Compare(arr, parent, child)) 109 | { 110 | temp = arr[child]; 111 | arr[child] = arr[parent]; 112 | arr[parent] = temp; 113 | PercolateUp(parent); 114 | } 115 | } 116 | 117 | public void Enqueue(T value) 118 | { 119 | if (count == CAPACITY) 120 | { 121 | DoubleSize(); 122 | } 123 | 124 | arr[count++] = value; 125 | PercolateUp(count - 1); 126 | } 127 | 128 | private void DoubleSize() 129 | { 130 | T[] old = arr; 131 | arr = new T[arr.Length * 2]; 132 | CAPACITY *= 2; 133 | Array.Copy(old, 0, arr, 0, count); 134 | } 135 | 136 | public T Dequeue() 137 | { 138 | if (count == 0) 139 | { 140 | throw new System.InvalidOperationException(); 141 | } 142 | 143 | T value = arr[0]; 144 | arr[0] = arr[count - 1]; 145 | count--; 146 | PercolateDown(0); 147 | return value; 148 | } 149 | 150 | public void Print() 151 | { 152 | for (int i = 0; i < count; i++) 153 | { 154 | Console.Write(arr[i] + " "); 155 | } 156 | Console.WriteLine(); 157 | } 158 | 159 | public bool IsEmpty() 160 | { 161 | return (count == 0); 162 | } 163 | 164 | public int Size() 165 | { 166 | return count; 167 | } 168 | 169 | public T Peek() 170 | { 171 | if (count == 0) 172 | { 173 | throw new System.InvalidOperationException(); 174 | } 175 | return arr[0]; 176 | } 177 | 178 | public static void HeapSort(int[] array, bool inc) 179 | { 180 | // Create max heap for increasing order sorting. 181 | PriorityQueue hp = new PriorityQueue(array, !inc); 182 | for (int i = 0; i < array.Length; i++) 183 | { 184 | array[array.Length - i - 1] = hp.Dequeue(); 185 | } 186 | } 187 | } 188 | 189 | 190 | 191 | /* 192 | Heap Array: 1 2 3 5 7 10 4 8 6 9 193 | 1 2 3 4 5 6 7 8 9 10 194 | Heap Array: 10 9 4 6 8 2 3 1 5 7 195 | 10 9 8 7 6 5 4 3 2 1 196 | */ -------------------------------------------------------------------------------- /AlgorithmsChapters/DP/OptimalBST.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class OptimalBST 4 | { 5 | private static int OptCostBst(int[] freq, int i, int j) 6 | { 7 | if (i > j) 8 | { 9 | return 0; 10 | } 11 | 12 | if (j == i) // one element in this subarray 13 | { 14 | return freq[i]; 15 | } 16 | 17 | int min = int.MaxValue; 18 | for (int r = i; r <= j; r++) 19 | { 20 | min = Math.Min(min, OptCostBst(freq, i, r - 1) + OptCostBst(freq, r + 1, j)); 21 | } 22 | return min + sum(freq, i, j); 23 | } 24 | 25 | public static int OptCostBst(int[] keys, int[] freq) 26 | { 27 | int n = freq.Length; 28 | return OptCostBst(freq, 0, n - 1); 29 | } 30 | 31 | public static int OptCostBstTD(int[] keys, int[] freq) 32 | { 33 | int n = freq.Length; 34 | int[,] cost = new int[n, n]; 35 | for (int i = 0; i < n; i++) 36 | for (int j = 0; j < n; j++) 37 | cost[i, j] = int.MaxValue; 38 | 39 | for (int i = 0; i < n; i++) 40 | { 41 | cost[i, i] = freq[i]; 42 | } 43 | 44 | return OptCostBstTD(freq, cost, 0, n - 1); 45 | } 46 | 47 | private static int OptCostBstTD(int[] freq, int[,] cost, int i, int j) 48 | { 49 | if (i > j) 50 | { 51 | return 0; 52 | } 53 | 54 | if (cost[i, j] != int.MaxValue) 55 | { 56 | return cost[i, j]; 57 | } 58 | 59 | int s = sum(freq, i, j); 60 | for (int r = i; r <= j; r++) 61 | { 62 | cost[i, j] = Math.Min(cost[i, j], OptCostBstTD(freq, cost, i, r - 1) + OptCostBstTD(freq, cost, r + 1, j) + s); 63 | } 64 | return cost[i, j]; 65 | } 66 | 67 | private static int sum(int[] freq, int i, int j) 68 | { 69 | int s = 0; 70 | for (int k = i; k <= j; k++) 71 | { 72 | s += freq[k]; 73 | } 74 | return s; 75 | } 76 | 77 | public static int OptCostBstBU(int[] keys, int[] freq) 78 | { 79 | int n = freq.Length; 80 | int[,] cost = new int[n, n]; 81 | 82 | for (int i = 0; i < n; i++) 83 | for (int j = 0; j < n; j++) 84 | cost[i, j] = int.MaxValue; 85 | 86 | for (int i = 0; i < n; i++) 87 | { 88 | cost[i, i] = freq[i]; 89 | } 90 | 91 | int sm = 0; 92 | for (int l = 1; l < n; l++) 93 | { // l is length of range. 94 | for (int i = 0, j = i + l; j < n; i++, j++) 95 | { 96 | sm = sum(freq, i, j); 97 | for (int r = i; r <= j; r++) 98 | { 99 | cost[i, j] = Math.Min(cost[i, j], sm + ((r - 1 >= i) ? cost[i, r - 1] : 0) + ((r + 1 <= j) ? cost[r + 1, j] : 0)); 100 | } 101 | } 102 | } 103 | return cost[0, n - 1]; 104 | } 105 | 106 | private static int[] SumInit(int[] freq, int n) 107 | { 108 | int[] sum = new int[n]; 109 | sum[0] = freq[0]; 110 | for (int i = 1; i < n; i++) 111 | { 112 | sum[i] = sum[i - 1] + freq[i]; 113 | } 114 | return sum; 115 | } 116 | 117 | private static int SumRange(int[] sum, int i, int j) 118 | { 119 | if (i == 0) 120 | { 121 | return sum[j]; 122 | } 123 | return sum[j] - sum[i - 1]; 124 | } 125 | 126 | public static int OptCostBstBU2(int[] keys, int[] freq) 127 | { 128 | int n = freq.Length; 129 | int[,] cost = new int[n, n]; 130 | for (int i = 0; i < n; i++) 131 | for (int j = 0; j < n; j++) 132 | cost[i, j] = int.MaxValue; 133 | 134 | int[] sumArr = SumInit(freq, n); 135 | for (int i = 0; i < n; i++) 136 | { 137 | cost[i, i] = freq[i]; 138 | } 139 | 140 | int sm = 0; 141 | for (int l = 1; l < n; l++) 142 | { // l is length of range. 143 | for (int i = 0, j = i + l; j < n; i++, j++) 144 | { 145 | sm = SumRange(sumArr, i, j); 146 | for (int r = i; r <= j; r++) 147 | { 148 | cost[i, j] = Math.Min(cost[i, j], sm + ((r - 1 >= i) ? cost[i, r - 1] : 0) + ((r + 1 <= j) ? cost[r + 1, j] : 0)); 149 | } 150 | } 151 | } 152 | return cost[0, n - 1]; 153 | } 154 | 155 | // Testing code. 156 | public static void Main(string[] args) 157 | { 158 | int[] keys = new int[] { 9, 15, 25 }; 159 | int[] freq = new int[] { 30, 10, 40 }; 160 | Console.WriteLine("OBST cost:" + OptCostBst(keys, freq)); 161 | Console.WriteLine("OBST cost:" + OptCostBstTD(keys, freq)); 162 | Console.WriteLine("OBST cost:" + OptCostBstBU(keys, freq)); 163 | Console.WriteLine("OBST cost:" + OptCostBstBU2(keys, freq)); 164 | } 165 | } 166 | 167 | /* 168 | OBST cost:130 169 | OBST cost:130 170 | OBST cost:130 171 | OBST cost:130 172 | */ --------------------------------------------------------------------------------