public bool CreatePath(Vector3 startPos, Vector3 targetpos) { bool pathSuccess = false; Node startNode = grid.NodeFromWorldPoint(startPos); Node targetNode = grid.NodeFromWorldPoint(targetpos); if (!startNode.walkAble && !targetNode.walkAble) { MyHeap <Node> openSet = new MyHeap <Node>(grid.MaxSize); HashSet <Node> closedSet = new HashSet <Node>(); openSet.Add(startNode); while (openSet.Count > 0) { Node currentNode = openSet.RemoveFirst(); closedSet.Add(currentNode); if (currentNode == targetNode) { //Success to find a path from A to B pathSuccess = true; break; } foreach (Node elm in grid.GetNeighbours(currentNode)) { //Cant walk on this node because of either bool or closedSet if (elm.walkAble || closedSet.Contains(elm)) { continue; } int newMovementCost = currentNode.gCost + GetDistance(currentNode, elm); if (newMovementCost < elm.gCost || !openSet.Contains(elm)) { elm.gCost = newMovementCost; elm.hCost = GetDistance(elm, targetNode); elm.parrent = currentNode; if (!openSet.Contains(elm)) { openSet.Add(elm); } else { openSet.UpdateItem(elm); } } } } } if (pathSuccess) { UpdateNodes(startNode, targetNode); } return(pathSuccess); }
/// <summary> /// take a list of char with weight is how frequent they appear in the file /// </summary> /// <param name="dict"></param> /// <returns></returns> public static Dictionary <char, string> Encode(Dictionary <char, float> dict) { var listNode = new List <Node <KeyValuePair <char, float> > >(); foreach (KeyValuePair <char, float> pair in dict) { listNode.Add(new Node <KeyValuePair <char, float> >(pair)); } var heap = new MyHeap <Node <KeyValuePair <char, float> > > (listNode, listNode.Count, (Node <KeyValuePair <char, float> > a, Node <KeyValuePair <char, float> > b) => a.data.Value.CompareTo(b.data.Value)); Node <KeyValuePair <char, float> > parent, leftChild, rightChild; int count = heap.Size; //KeyValuePair<char, float> pair; while (count > 1) { leftChild = heap.Pop(); rightChild = heap.Pop(); parent = new Node <KeyValuePair <char, float> >( new KeyValuePair <char, float>('?', leftChild.data.Value + rightChild.data.Value), leftChild, rightChild); heap.Push(parent); count--; } var list = new Dictionary <char, string>(); var root = heap.Pop(); return(Translate(root, list, "")); }
public ProgramState() { ExeStack = new MyStack <IStatement>(); SymTable = new MyDictionary <string, int>(); FileTable = new MyFileTable <Tuple <string, FileStream> >(); Heap = new MyHeap <int>(); }
public void GivenAnEmptyHeap_WhenInsertNewValues_ShouldAddThoseValuesOnArray() { // Arrange var heap = new MyHeap(); // Act heap.Insert(10, 5, 17); // Assert heap.GetAll().Should().BeEquivalentTo(17, 5, 10); }
public void GivenAHeapWithSomeItems_WhenRemoveTheRootValue_ShouldRebalanceTheHeap() { // Arrange var heap = new MyHeap(); heap.Insert(10, 5, 17, 4, 22); // Act heap.Remove(); // Assert heap.GetAll().First().Should().Be(17); }
public void GivenAHeapWithSomeItems_ShouldTheKthLargestItem(int k, int largestExpected) { // Arrange var heap = new MyHeap(); heap.Insert(new int[] { 5, 10, 8, 7, 2 }); // Act var largest = Exercises.FindKthLasgestItem(heap, k); // Assert largest.Should().Be(largestExpected); }
public void TestMinHeap() { var minHeapComparer = new HeapItemComparer <int>(true); var heap = new MyHeap <int>(10, minHeapComparer); heap.Insert(1); heap.Insert(20); heap.Insert(300); heap.Insert(4000); heap.Insert(25000); var root = heap.Remove(); Assert.IsTrue(root == 3); }
public List <PrgState <T> > SetStateList(T stmt) { MyList output = new MyList(); MyDictionary symTable = new MyDictionary(); MyStack <T> exeStack = new MyStack <T>(); MyIHeap heap = new MyHeap(); PrgState <T> prog = new PrgState <T>(exeStack, symTable, output, heap, 1); prog.AddExeStack(stmt); List <PrgState <T> > progList = new List <PrgState <T> >(); progList.Add(prog); return(progList); }
void testHeap() { int[] arr = new int[10]; var rnd = new Random(101); for (int i = 0; i < 10; i++) { arr[i] = rnd.Next(1, 100); } Func <int, int, int> cmp = (x, y) => x - y; var h = new MyHeap <int>(arr, cmp); for (int i = 0; i < 10; i++) { var min = h.PopMin(); } }
static void Main(string[] args) { Console.WriteLine("Hello World!"); int[] arr = { 1, 2, 3, 3, 4, 5, 5, 8, 10, 10 }; //var a = BubbleSort.GetSorted(arr); // QuickSort.GetSorted(arr); MyHeap.BuildHead(); //foreach (var x in a) //{ // Console.WriteLine(x); //} var a = removeDuplicates(arr, arr.Length); // Print updated array for (int i = 0; i < a; i++) { Console.Write(arr[i] + " "); } var b = BianrySearch(arr, 225, 0, arr.Length - 1); Console.WriteLine(b); BinaryTree bt = new BinaryTree(); BinaryTree bt1 = new BinaryTree(); var root = bt.Insert(null, 10); var root1 = bt1.Insert(null, 10); /*root = bt.Insert(root, 20); * root = bt.Insert(root, 8); * root = bt.Insert(root, 9); * root = bt.Insert(root, 15); * root = bt.Insert(root, 25); */ bt.Insert(root, 20); bt.Insert(root, 8); bt.Insert(root, 9); bt.Insert(root, 15); bt.Insert(root, 25); bt.Insert(root, 12); bt.Insert(root, 5); bt1.Insert(root1, 20); bt1.Insert(root1, 8); bt1.Insert(root1, 9); bt1.Insert(root1, 15); bt1.Insert(root1, 25); //bt1.Insert(root1, 12); bt1.Insert(root1, 7); TwoNodes tn = new TwoNodes { First = bt.RootNode, Second = bt1.RootNode }; Console.WriteLine("Is_BST_Identical_Iterative ::{0} ", bt.Is_BST_Identical_Iterative(tn)); Console.WriteLine("Is_BST_Identical ::{0} ", bt.isIdentical(bt.RootNode, bt1.RootNode)); bt1.Height_Tree_Iterative(bt1.RootNode); Console.WriteLine("PreOrder"); bt.PreOrder(bt.RootNode); Console.WriteLine(""); Console.WriteLine("InOrder"); bt.InOrder(bt.RootNode); Console.WriteLine(""); Console.WriteLine("PostOrder"); bt.PostOrder(bt.RootNode); bt.CreateBinaryTreeFromInAndPreOrder(); Console.WriteLine(""); Console.WriteLine("Find"); var f = bt.Find(115, bt.RootNode); Console.WriteLine(f != null ? f.data : 0); Console.WriteLine(""); Console.WriteLine("MinValue"); var m = bt.GetMinValue(bt.RootNode); Console.WriteLine(m); int pos = 6; bt.GetKthMinValue(bt.RootNode, ref pos); //bt.LevelOrder(bt.RootNode); //bt.Inorder_Iterative(bt.RootNode); //bt.Preorder_Iterative(bt.RootNode); //bt.Postorder_Iterative(bt.RootNode); //bt.Get_Inorder_Predecessor(bt.RootNode); //bt.Get_Inorder_Successor(bt.RootNode); Console.WriteLine("\nInvert binary"); bt.InvertBinary(bt.RootNode); bt.LevelOrder(bt.RootNode); Node ln = new Node { data = 20 }; Node rn = new Node { data = 30 }; Node no = new Node { data = 10, Left = ln, Right = rn }; // Console.WriteLine("isBST :: {0}", bt.isBST(no, int.MinValue) ); Console.WriteLine("isBST :: {0}", bt.isBinarySearch(no)); AVLTree at = new AVLTree(); at.Avl_execute(); int[] arr1 = { 5, 6, 8, 9, 10, 12, 15, 20 }; GetTriplets(arr1, 30); GetSumDobles(arr1, 15); GetSumDobles_Linear(arr1, 15); Console.WriteLine("KnapSack"); int[] val = new int[] { 60, 120, 100 }; int[] wt = new int[] { 10, 30, 20 }; int Cap = 50; int n = val.Length; int[,] dp = new int[n + 1, Cap + 1]; KnapSack k = new KnapSack(); Console.WriteLine(k.KnapSack_Binary(Cap, wt, val, n, dp)); k.KnapSack_Fraction(Cap, wt, val, n); Console.WriteLine("Pattern"); Pattern.SearchPattern("AABAACAADAABAAABAACAAD", "CAAD"); Pattern.Binary_MultipleOf3("110100000101"); Console.WriteLine("Largest Sum Contiguous Subarray"); int[] aa = { 1, 2, 3, -2, 5 }; Pattern.maxSubArraySum(aa); Console.WriteLine("Missing elements"); int[] aa1 = { 1, 2, 3, 5, 7, 8, 10 }; Pattern.FindMissingElements(aa1); int[] aa2 = { 1, 2, 3, 1, 1 }; Pattern.FindMajorityElement(aa2); //Search in a Rotated Array int[] aa3 = { 5, 6, 7, 8, 9, 10, 1, 2, 3, 4 }; Pattern.SearchRotatedArray(aa3, 10); //Linked List LinkedList lst = new LinkedList(); lst.InsertFront(10); lst.InsertLast(20); lst.InsertFront(5); lst.InsertLast(25); lst.InsertLast(35); lst.PrintList(lst); lst.FindMiddleElement(lst); Problem_30 p30 = new Problem_30(); p30.FindSingeNumber(); p30.HappyNumber(); p30.Longest_Sum_Subarray(); p30.FindSubarraySum(); p30.MoveZeroRight(); p30.MaxProfit(); p30.IsAnagram(); p30.StringSorting("kgadeA"); p30.GroupingAnagrams(); p30.CountingElement(); p30.BackspaceStingCompare(); //p30.LastStoneWeight(); p30.SubArrayWithEqualZeroAndOne(); p30.StringShif(); p30.ProductOfArrayExceptSlef(); Console.WriteLine("\nValid parenthesis:: {0}", p30.ValidParenthesis()); p30.NumberOfIsland(); p30.LeftmostColumnWithAtleastOne(); p30.BitwiseAnd(); p30.JumpingProblem(); p30.LongestcommonSubsequence(); p30.CountPairsGivenSum(); p30.MaximumPathSum(bt.RootNode); p30.ValidSequence(bt.RootNode); p30.MinFromSatck(); p30.MinimumPathSum(); p30.HistogramMaxRectangle(); //p30.Print_Combination_R_Elements_Array(); ///All Array Problem /// ArrayProblem ar = new ArrayProblem(); ar.Find_And_Print_SubArraySum(); ar.SortBinaryArray(); ar.FindDuplicate(); ar.LongestConsecutiveSubArray(); ar.MaximumSumSubArray(); ar.MinimuSumSubArray(); ar.SubArrayWithEqualZeroAndOne(); ar.SortArrayOnlyZeroOneTwos(); ar.Merge2SortedArray(); ar.MergeArray_ReplaceZeroValue(); ar.Find_Index_MaxLength_ContinuousOnes(); ar.ProductOfTwoIntArray(); ar.Suffle(); ar.RearrangeArrayHighAndLow(); ar.EquilibriumIndex(); ar.FindMajorityElement(); ar.MoveAllZeroToEnd(); ar.ProductOfArrayWithotSlef(); ar.BitonicSubArray(); ar.FindMaximumDifference(); ar.MaximumSumCircularSubArray(); ar.FindSumMimumSubArray_Given_Size(); ar.FindSumSubArray_Given_Sum(); ar.LengthOfSmallestSubarray_SumOfElements_GreaterThanNumber(); ar.Find_Smallest_Window_Will_Make_Entire_Array_Sorted(); ar.TrappingRainWaterwithin_given_set_bars(); ar.Find_Maximum_Sum_Subsequence_With_NO_Adjacent(); ar.MinimumNumber_Platform(); ar.LengthOf_Continuous_Same_Sum_Two_Binary_Array(); ar.Find_Number_Rotations(); ar.RodCutting(); ar.Find_kth_Smallest_Element(); ar.FindAllCombinations(); //Trie data structure Trie tr = new Trie(); string[] words = { "abc", "abgl", "cdf", "abcd", "lmn" }; //string[] words = { "abc"}; foreach (string st in words) { tr.Insert(st); } Console.WriteLine("\nIs string present {0} ", tr.Search("cdf")); tr.AutoComplete("ab"); // List of graph edges as per above diagram List <Edge> edges = new List <Edge> { // Notice that node 0 is unconnected node new Edge(1, 2), new Edge(1, 7), new Edge(1, 8), new Edge(2, 3), new Edge(2, 6), new Edge(3, 4), new Edge(3, 5), new Edge(8, 9), new Edge(8, 12), new Edge(9, 10), new Edge(9, 11) }; // Set number of vertices in the graph (0-12) int N = 13; // create a graph from edges Graph graph = new Graph(edges, N); // stores vertex is discovered or not bool[] discovered = new bool[N]; // Do DFS traversal from all undiscovered nodes to // cover all unconnected components of graph for (int i = 0; i < N; i++) { if (!discovered[i]) { graph.DFS(graph, i, discovered); } } //Matrix Matrix mt = new Matrix(); mt.Print_SpiralOrder(); mt.Rotation_90(); mt.FloodFill(); }
private IEnumerator FindPath(Vector3 startPos, Vector3 targetpos) { Vector3[] wayPoints = new Vector3[0]; bool pathSuccess = false; Node startNode = grid.NodeFromWorldPoint(startPos); Node targetNode = grid.NodeFromWorldPoint(targetpos); if (!startNode.walkAble && !targetNode.walkAble) { MyHeap <Node> openSet = new MyHeap <Node>(grid.MaxSize); HashSet <Node> closedSet = new HashSet <Node>(); openSet.Add(startNode); while (openSet.Count > 0) { Node currentNode = openSet.RemoveFirst(); closedSet.Add(currentNode); if (currentNode == targetNode) { //Success to find a path from A to B pathSuccess = true; break; } foreach (Node elm in grid.GetNeighbours(currentNode)) { //Cant walk on this node because of either bool or closedSet if (elm.walkAble || closedSet.Contains(elm)) { continue; } int newMovementCost = currentNode.gCost + GetDistance(currentNode, elm); if (newMovementCost < elm.gCost || !openSet.Contains(elm)) { elm.gCost = newMovementCost; elm.hCost = GetDistance(elm, targetNode); elm.parrent = currentNode; if (!openSet.Contains(elm)) { openSet.Add(elm); } else { openSet.UpdateItem(elm); } } } } } yield return(null); if (pathSuccess) { wayPoints = RetracePath(startNode, targetNode); } requestManager.FinishedProcessingPath(wayPoints, pathSuccess); }
SrchRec[] calcDiff(MyWord[][] arr, int nRow) { int max_res = 1000; int max_d = 1000; var begin = Environment.TickCount; var res = new SrchRec[arr[0].Length]; for (int i = 0; i < arr[0].Length; i++) { res[i] = new SrchRec() { path = new int[] { i }, d = 0 }; } for (var row = 1; row < nRow; row++) { var lst = arr[row]; var prevLst = arr[row - 1]; var tmplRes = new List <int[]>(); for (var j = 0; j < res.Length; j++) { var prevD = res[j].d; var prevI = res[j].path[row - 1]; var prevW = prevLst[prevI]; for (var k = 0; k < lst.Length; k++) { var curW = lst[k]; if (prevW.titleId == curW.titleId) { //var d = wordDiff(res[j].w, lst[k]); var d = Convert.ToInt32(prevW.parId) - Convert.ToInt32(curW.parId); d *= d < 0 ? -100 : 100; d += Math.Abs(prevW.pos - curW.pos) * 10; d += prevD; tmplRes.Add(new int[] { j, k, d }); } } } var h = new MyHeap <int[]>(tmplRes.ToArray(), (x, y) => x[2] - y[2]); var n = Math.Min(max_res, tmplRes.Count); var top = new SrchRec[n]; for (int i = 0; i < n; i++) { var t = h.PopMin(); //chk distance if (t[2] > max_d) { Array.Resize(ref top, i); break; } var newRec = new SrchRec() { d = t[2], path = new int[row + 1] }; res[t[0]].path.CopyTo(newRec.path, 0); newRec.path[row] = t[1]; top[i] = newRec; } res = top; } var elapsed = Environment.TickCount - begin; Debug.WriteLine("calc diff {0}", elapsed); foreach (var item in res) { var row = 0; item.detail = item.path.Select(v => arr[row++][v]).ToList(); } return(res); }
private void addProgram() { IStmt st1 = new AssignStmt("v", new ConstExp(10)); IStmt st2 = new NewStmt("a", new ConstExp(22)); IStmt st3 = new AssignStmt("v", new ConstExp(32)); IStmt st4 = new PrintStmt(new VarExp("v")); IStmt st5 = new PrintStmt(new ReadHeapExp("a")); IStmt st8 = new ForkStmt(new CmpStmt(new WriteHeapStmt("a", new ConstExp(30)), new CmpStmt(st3, new CmpStmt(st4, st5)))); IStmt st6 = new PrintStmt(new VarExp("v")); IStmt st7 = new PrintStmt(new ReadHeapExp("a")); IStmt prgStmt = new CmpStmt(st1, new CmpStmt(st2, new CmpStmt(st8, new CmpStmt(st6, st7)))); //IStmt prgStmt = addNewStmt(); IStack<IStmt> exeStk = new ArrayStack<IStmt>(); IDictionary<String, int> tbl = new ArrayDictionary<String, int>(); IList<int> outl = new ArrayList<int>(); IHeap<int> h = new MyHeap<int>(); exeStk.Push(prgStmt); PrgState crtPrg = new PrgState(exeStk, tbl, outl, h); ctrl.addPrgState(crtPrg); ctrl.repoSer (); try { mainMenu(); } catch (ControllerException) { Console.WriteLine("Step evaluation error."); } catch (RepositoryException) { Console.WriteLine("Program state error."); } catch (ConsoleException) { Console.WriteLine("Wrong option. Try again."); } }