Tuesday, November 29, 2016


#codingexercise
Generate Lexicographically ordered permutations of a string
        static void Permute(String a, StringBuilder b, bool[] used, int start, int end, ref SortedList<String, String> permutations)
        {
              if ( b.Length == end-start+1)  { permutations.Add(b.ToString(),b.ToString()); return;}
              for (int i = start; i <= end ; i++)
              {
                 if (used[i]) continue;
                 used[i] = true;
                 b  = b.Append(a[i]);
                 Permute(a, b, used, start, end, ref permutations);
                 b.Length--;
                 used[i] = false;
              }
        }
        static void ToPrint(SortedList<String, String> permutations, string prefix)
        {
            Console.WriteLine("---------------------------------------");
            for (int i = 0; i < permutations.Count; i++)
                Console.WriteLine(prefix + permutations.ElementAt(i).Key);
            Console.WriteLine("---------------------------------------");
        }
        static void Main(string[] args)
        {
            var a = "321";
            var b = new StringBuilder();
            var used = new bool[a.Length];
            int start = 0;
            int end = a.Length - 1;
            var permutations = new SortedList<String, String>();
            Permute(a, b, used, start, end, ref permutations);
            var prefix = String.Empty;
            ToPrint(permutations, prefix);
        }
---------------------------------------
123
132
213
231
312
321
---------------------------------------

 AVL tree delete  
We described AVL tree insertion here. We now look at the AVL tree delete. 
Node Remove(Node root, int k) 
If (root ==null) return null; 
If (k < root.data) 
Root.left = Remove(root.left, k); 
Else if (k > root.data) 
Root.right =  Remove(root.right, k); 
Else 
Node left = root.left; 
Node right = root.right; 
Delete root; 
If (!right) return left; 
Node min = FindMin(right); 
Min.right = Removemin(min); 
Min.left = left; 
Return Balance(min); 
Return Balance(root); 
}

Node RemoveMin(Node root) 
{ 
If (root.left) 
Return root.right; 
Root.left = RemoveMin(root.left); 
Return Balance(root); 
} 
Node FindMin(Node root) 
{ 
Return (root.left != null ? FindMin(root.left) : root; 
}

No comments:

Post a Comment