Dequeue() public method

public Dequeue ( ) : string
return string
        public void TestPriorityQueue()
        {
            int operationsCount = 100000;

            Random rand = new Random(0);

            PriorityQueue<double> queue = new PriorityQueue<double>();

            for (int op = 0; op < operationsCount; ++op)
            {
                int opType = rand.Next(0, 2);

                if (opType == 0) // Enqueue
                {
                    double item = (100.0 - 1.0) * rand.NextDouble() + 1.0;
                    queue.Enqueue(item);

                    Assert.IsTrue(queue.IsConsistent(), "Test fails after enqueue operation # " + op);
                }
                else // Dequeue
                {
                    if (queue.Count > 0)
                    {
                        double item = queue.Dequeue();
                        Assert.IsTrue(queue.IsConsistent(), "Test fails after dequeue operation # " + op);
                    }
                }
            }
        }
Esempio n. 2
0
        static void Main()
        {
            PriorityQueue<int> queue = new PriorityQueue<int>();
            queue.Enqueue(10);
            queue.Enqueue(3);
            queue.Enqueue(14);
            queue.Enqueue(12);
            queue.Enqueue(5);
            queue.Enqueue(2);

            Console.WriteLine("Printing the queue");
            foreach (var item in queue)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("Dequeue {0}", queue.Dequeue());
            Console.WriteLine("Dequeue {0}", queue.Dequeue());

            Console.WriteLine("Printing the queue again");
            foreach (var item in queue)
            {
                Console.WriteLine(item);
            }
        }
Esempio n. 3
0
    /* 1 Implement a class PriorityQueue<T> based
     * on the data structure "binary heap".
     * */
    static void Main(string[] args)
    {
        var heap = new Heap<int>();
        heap.Add(1);
        heap.Add(2);
        heap.Add(3);

        Debug.Assert(heap.SameContents(new[] { 1, 2, 3 }));
        Console.WriteLine(string.Join(",", heap));

        Debug.Assert(heap.ChopHead() == 3);
        Debug.Assert(heap.ChopHead() == 2);
        Debug.Assert(heap.ChopHead() == 1);
        Debug.Assert(heap.IsEmpty);

        // higher string means lower priority
        var pqueue = new PriorityQueue<string, string>((s1, s2) => -s1.CompareTo(s2));

        pqueue.Enqueue("18:00", "Buy food");
        pqueue.Enqueue("06:00", "Walk dog");
        pqueue.Enqueue("21:00", "Do homework");
        pqueue.Enqueue("09:00", "Go to work");
        pqueue.Enqueue("21:00", "Drink beer");

        Debug.Assert(pqueue.Count == 5);

        Debug.Assert(pqueue.Dequeue() == "Walk dog");
        Debug.Assert(pqueue.Dequeue() == "Go to work");
        Debug.Assert(pqueue.Dequeue() == "Buy food");
        Debug.Assert(new[] { "Do homework", "Drink beer" }.Contains(pqueue.Dequeue()));
        Debug.Assert(new[] { "Do homework", "Drink beer" }.Contains(pqueue.Dequeue()));
    }
        public void CorrectPriorityTest1()
        {
            PriorityQueue<int> queue = new PriorityQueue<int>();

            queue.Enqueue(-12);
            queue.Enqueue(512);
            queue.Enqueue(77);
            queue.Enqueue(-1);
            queue.Enqueue(82);
            queue.Enqueue(92);
            queue.Enqueue(-111);
            queue.Enqueue(-151);
            queue.Enqueue(512);
            queue.Enqueue(55);

            Assert.AreEqual(10, queue.Count);
            Assert.AreEqual(512, queue.Dequeue());
            Assert.AreEqual(512, queue.Dequeue());
            Assert.AreEqual(92, queue.Dequeue());
            Assert.AreEqual(82, queue.Dequeue());
            Assert.AreEqual(77, queue.Dequeue());
            Assert.AreEqual(55, queue.Dequeue());
            Assert.AreEqual(-1, queue.Dequeue());
            Assert.AreEqual(-12, queue.Dequeue());
            Assert.AreEqual(-111, queue.Dequeue());
            Assert.AreEqual(-151, queue.Dequeue());
        }
Esempio n. 5
0
 public void DequeueTest()
 {
     var testQueue = new PriorityQueue<int>();
     testQueue.Enqueue(10, 0);
     testQueue.Enqueue(5, 0);
     testQueue.Enqueue(6, 1);
     Assert.IsTrue(testQueue.Dequeue() == 6);
     Assert.IsTrue(testQueue.Dequeue() == 10);
     Assert.IsTrue(testQueue.Dequeue() == 5);
 }
Esempio n. 6
0
        public static void Main(string[] args)
        {
            var priorityQueue = new PriorityQueue<int>();
            priorityQueue.Enqueue(3, 3);
            priorityQueue.Enqueue(3, 3);
            priorityQueue.Enqueue(4, 4);
            priorityQueue.Dequeue();
            priorityQueue.Dequeue();

            Console.WriteLine(priorityQueue.Peek());
        }
        public static void Main()
        {
            var minPriorityQueue = new PriorityQueue<int>();

            minPriorityQueue.Enqueue(12);
            minPriorityQueue.Enqueue(3);
            minPriorityQueue.Enqueue(7);

            Console.WriteLine(minPriorityQueue.Dequeue());
            Console.WriteLine(minPriorityQueue.Dequeue());
            Console.WriteLine(minPriorityQueue.Dequeue());
        }
Esempio n. 8
0
        public void Simple()
        {
            var priorityQueue1 = new PriorityQueue<int, int>(PriorityQueueType.Minimum);
            priorityQueue1.Enqueue(4);

            Assert.AreEqual(priorityQueue1.Count, 1);
            Assert.AreEqual(priorityQueue1.Dequeue(), 4);

            priorityQueue1.Enqueue(5);
            priorityQueue1.Enqueue(6, 2);

            Assert.AreEqual(priorityQueue1.Dequeue(), 5);
            Assert.AreEqual(priorityQueue1.Dequeue(), 6);

            priorityQueue1.Enqueue(6, 2);
            priorityQueue1.Enqueue(5);

            Assert.AreEqual(priorityQueue1.Dequeue(), 5);
            Assert.AreEqual(priorityQueue1.Dequeue(), 6);

            var priorityQueue2 = new PriorityQueue<string, int>(PriorityQueueType.Minimum);

            priorityQueue2.Enqueue("a", 1);
            priorityQueue2.Enqueue("b", 2);
            priorityQueue2.Enqueue("c", 3);
            priorityQueue2.Enqueue("d", 4);
            priorityQueue2.Enqueue("e", 5);
            priorityQueue2.Enqueue("f", 6);

            priorityQueue2.Enqueue("z", 6);
            priorityQueue2.Enqueue("y", 5);
            priorityQueue2.Enqueue("x", 4);
            priorityQueue2.Enqueue("w", 3);
            priorityQueue2.Enqueue("v", 2);
            priorityQueue2.Enqueue("u", 1);

            priorityQueue2.Enqueue("z", 1);
            priorityQueue2.Enqueue("y", 2);
            priorityQueue2.Enqueue("x", 3);
            priorityQueue2.Enqueue("w", 4);
            priorityQueue2.Enqueue("v", 5);
            priorityQueue2.Enqueue("u", 6);

            Assert.AreEqual(priorityQueue2.Count, 18);

            priorityQueue2.Clear();

            Assert.AreEqual(priorityQueue2.Count, 0);
        }
Esempio n. 9
0
        public void Enqueue()
        {
            var priorityQueue = new PriorityQueue<string, int>(PriorityQueueType.Maximum) { DefaultPriority = 2 };
            priorityQueue.Enqueue("test1");
            priorityQueue.Enqueue("test2", 3);

            Assert.AreEqual(priorityQueue.Dequeue(), "test2");
            Assert.AreEqual(priorityQueue.Dequeue(), "test1");

            priorityQueue.Enqueue("test1");
            priorityQueue.Enqueue("test2", 1);

            Assert.AreEqual(priorityQueue.Dequeue(), "test1");
            Assert.AreEqual(priorityQueue.Dequeue(), "test2");
        }
Esempio n. 10
0
 public static void Main(string[] args)
 {
     PriorityQueue<int> heap = new PriorityQueue<int>(2);
     heap.Enqueue(1);
     heap.Enqueue(2);
     heap.Enqueue(3);
     heap.Enqueue(4);
     heap.Dequeue();
     heap.Enqueue(3);
     heap.Enqueue(5);
     Console.WriteLine(heap.Dequeue());
     heap.Print();
     heap.Enqueue(2);
     heap.Print();
 }
Esempio n. 11
0
    private static void Main()
    {
        var items = new[] { 2, 6, 3, 2, 1, 7, 4, 9, 5, 1, 8 };
        Console.WriteLine("Items: [{0}]", string.Join(", ", items));


        // Priority queue of integers, where a lower number means higher priority
        var queue = new PriorityQueue<int>();        

        // Add each item to the priority queue and 
        // check if the item with the highest priority is at the top of the queue
        var minItem = int.MaxValue;
        foreach (var item in items)
        {
            queue.Enqueue(item);
            minItem = Math.Min(item, minItem);            
            Debug.Assert(queue.Peek() == minItem);
        }

        // Now check if after each dequeue, the items come out ranked by priority
        var sorted = new List<int>();
        while (queue.Count > 0)
        {
            sorted.Add(queue.Dequeue());
        }

        // Items should be sorted in ascending order
        Console.WriteLine("Queue items: [{0}]", string.Join(", ", sorted));
    }
Esempio n. 12
0
        public static void Main()
        {
            var queue = new PriorityQueue<string>();

            queue.Enqueue("Pesho");
            queue.Enqueue("Ivan");
            queue.Enqueue("Maria");
            queue.Enqueue("Stamat");
            queue.Enqueue("Bai Ivan");

            Console.WriteLine(queue.Dequeue());
            Console.WriteLine(queue.Dequeue());
            Console.WriteLine(queue.Dequeue());
            Console.WriteLine(queue.Dequeue());
            Console.WriteLine(queue.Dequeue());
        }
Esempio n. 13
0
        public static void Main()
        {
            PriorityQueue<int> priorityQueue = new PriorityQueue<int>(true);

            priorityQueue.Enqueue(100);
            priorityQueue.Enqueue(19);
            priorityQueue.Enqueue(36);
            priorityQueue.Enqueue(17);
            priorityQueue.Enqueue(3);
            priorityQueue.Enqueue(25);
            priorityQueue.Enqueue(1);
            priorityQueue.Enqueue(27);
            priorityQueue.Enqueue(22);
            priorityQueue.Enqueue(100);
            priorityQueue.Enqueue(111);
            priorityQueue.Enqueue(222);
            priorityQueue.Enqueue(100);
            priorityQueue.Enqueue(100);
            priorityQueue.Enqueue(324100);
            priorityQueue.Enqueue(32);
            priorityQueue.Enqueue(4);

            while (priorityQueue.Count > 0)
            {
                Console.WriteLine(priorityQueue.Dequeue());
            }
        }
Esempio n. 14
0
    public static Path<Tile> FindPath(
        Tile start,
        Tile destination)
    {
        var closed = new HashSet<Tile>();
        var queue = new PriorityQueue<double, Path<Tile>>();
        queue.Enqueue(0, new Path<Tile>(start));

        while (!queue.IsEmpty)
        {
            var path = queue.Dequeue();

            if (closed.Contains(path.LastStep))
                continue;
            if (path.LastStep.Equals(destination))
                return path;

            closed.Add(path.LastStep);

            foreach (Tile n in path.LastStep.Neighbours)
            {
                double d = distance(path.LastStep, n);
                var newPath = path.AddStep(n, d);
                queue.Enqueue(newPath.TotalCost + estimate(n, destination), 
                    newPath);
            }
        }

        return null;
    }
Esempio n. 15
0
    static void Main()
    {
        Console.WriteLine("Creating an instance of the custom PriorityQueue class and adding 8 integers to it in non-increasing randomized order.");
        var priorityQueue = new PriorityQueue<int>();
        priorityQueue.Enqueue(5);
        priorityQueue.Enqueue(3);
        priorityQueue.Enqueue(2);
        priorityQueue.Enqueue(5);
        priorityQueue.Enqueue(15);
        priorityQueue.Enqueue(6);
        priorityQueue.Enqueue(0);
        priorityQueue.Enqueue(-8);

        Console.WriteLine("Printing the queue:");
        PrintQueue(priorityQueue);

        Console.WriteLine("Dequeuing and displaying the first 5 elements");
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Dequeuing the number {0}", priorityQueue.Dequeue());
        }

        Console.WriteLine("Printing the queue after the removal:");
        PrintQueue(priorityQueue);

        Console.WriteLine("Adding 5 more integers to the queue in non-increasing randomized order.");
        priorityQueue.Enqueue(9);
        priorityQueue.Enqueue(20);
        priorityQueue.Enqueue(13);
        priorityQueue.Enqueue(2);
        priorityQueue.Enqueue(7);

        Console.WriteLine("Printing the queue after the addition:");
        PrintQueue(priorityQueue);
    }
Esempio n. 16
0
    static void DjikstraAlgo(Dictionary<Node, List<Connection>> graph, Node source)
    {
        PriorityQueue<Node> queue = new PriorityQueue<Node>();

        foreach (var node in graph)
        {
            node.Key.DjikstraDistance = long.MaxValue;
        }

        source.DjikstraDistance = 0;
        queue.Enqueue(source);

        while (queue.Count != 0)
        {
            Node currentNode = queue.Dequeue();

            if (currentNode.DjikstraDistance == long.MaxValue)
            {
                break;
            }

            foreach (var connection in graph[currentNode])
            {
                var potDistance = currentNode.DjikstraDistance + connection.Distance;

                if (potDistance < connection.ToNode.DjikstraDistance)
                {
                    connection.ToNode.DjikstraDistance = potDistance;
                    queue.Enqueue(connection.ToNode);
                }
            }
        }
    }
Esempio n. 17
0
        public void PriorityQueue_Dequeue_NonRepeatedValues_Success()
        {
            // Arrange
            var priorityQueue = new PriorityQueue<int>();
            var values = new int[] { 10, 7, 6, 1, 2, 3, 5, 4, 9, 8 };
            var expected = "1,2,3,4,5,6,7,8,9,10";

            // Act
            foreach (var value in values)
            {
                priorityQueue.Enqueue(value);
            }

            var result = "";
            var index = 0;
            var lastIndex = priorityQueue.Count() - 1;

            while (!priorityQueue.IsEmpty())
            {
                var element = priorityQueue.Dequeue();

                result += index++ == lastIndex ?
                    string.Format("{0}", element.ToString()) : string.Format("{0},", element.ToString());
            }

            // Assert
            Assert.AreEqual(result, expected);
        }
Esempio n. 18
0
    /* Task 1:  
     * Implement a class PriorityQueue<T> based on the data structure "binary heap".
     */

    static void Main(string[] args)
    {
        var prioQueue = new PriorityQueue<int>();

        prioQueue.Add(25);
        prioQueue.Add(15);
        prioQueue.Add(105);
        prioQueue.Add(5);
        prioQueue.Add(35);

        Console.WriteLine(prioQueue.Count());
        Console.WriteLine(prioQueue.Dequeue());
        Console.WriteLine(prioQueue.Dequeue());
        Console.WriteLine(prioQueue.Dequeue());
        Console.WriteLine(prioQueue.Dequeue());
    }
Esempio n. 19
0
    public static void DijkstraAlgorithm(Graph graph, Node source)
    {
        foreach (var node in graph)
        {
            node.MinDistance = double.PositiveInfinity;
        }

        source.MinDistance = 0;

        var pQueue = new PriorityQueue<Node>();
        pQueue.Enqueue(source);

        while (pQueue.Count != 0)
        {
            Node currentNode = pQueue.Dequeue();

            foreach (var neighbour in graph[currentNode.Id].Neighbors)
            {
                double newDist = currentNode.MinDistance + neighbour.Distance;

                if (newDist < neighbour.Node.MinDistance)
                {
                    neighbour.Node.MinDistance = newDist;
                    pQueue.Enqueue(neighbour.Node);
                }
            }
        }
    }
Esempio n. 20
0
    void FindPathPQ(Vector3 startPos, Vector3 targetPos, int x)
    {
        Node3d startNode = grid.NodeFromWorldPoint (startPos);
        Node3d targetNode = grid.NodeFromWorldPoint (targetPos);
        PriorityQueue<Node3d> openSet = new PriorityQueue<Node3d> ();
        HashSet<Node3d> closedSet = new HashSet<Node3d> ();
        openSet.Enqueue (startNode.fCost, startNode);
        while (openSet.Count > 0) {
            //get the lowest fCost in openSet, o(1)
            Node3d currentNode = openSet.Dequeue ();
            closedSet.Add (currentNode);

            if (currentNode == targetNode) {
                RetracePath (startNode, targetNode, x);
                return;
            }
            foreach (Node3d neighbor in grid.GetNeighbors(currentNode)) {
                if (!neighbor.walkable || closedSet.Contains (neighbor)) {
                    continue;
                }

                int newMovementCostToNeighbor = currentNode.gCost + GetDistance (currentNode, neighbor);
                //contains is constant because custom PQ uses another Dict<node,bool> to track values added
                if (newMovementCostToNeighbor < neighbor.gCost || !openSet.Contains (neighbor)) {
                    neighbor.gCost = newMovementCostToNeighbor;
                    neighbor.hCost = GetDistance (neighbor, targetNode);
                    neighbor.parent = currentNode;

                    if (!openSet.Contains (neighbor)) {
                        openSet.Enqueue (neighbor.fCost, neighbor);
                    }
                }
            }
        }
    }
Esempio n. 21
0
    //-------------------------------------Movement-----------------------------------------//
    // A* algorithm to find shortest path to desired tile.
    private Path<Tile> findShortestPath(Tile start, Tile end)
    {
        PriorityQueue<int, Path<Tile>> open = new PriorityQueue<int, Path<Tile>>();
        HashSet<Tile> closed = new HashSet<Tile>();
        open.Enqueue(0, new Path<Tile>(start));
        int cost = 1;

        while (!open.isEmpty())
        {
            var path = open.Dequeue();
            if (closed.Contains(path.LastStep))
            {
                continue;
            }
            if (path.LastStep.Equals(end))
            {
                return path;
            }
            closed.Add(path.LastStep);
            foreach (Tile t in path.LastStep.connectedTiles)
            {
                if (t.isBlocked)
                {
                    closed.Add(t);
                    continue;
                }

                var newPath = path.AddStep(t, cost);
                open.Enqueue(newPath.TotalCost, newPath);
            }
        }
        return null;
    }
    // Dijkstra's shortest paths algorithm, implemented
    // with priority queue. Running time: O(M * log M)
    // Learn more at: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Using_a_priority_queue
    public static void DijkstraAlgorithm(
        Dictionary<Node, List<Edge>> graph, Node sourceNode)
    {
        var queue = new PriorityQueue<Node>();

        foreach (var node in graph)
        {
            node.Key.Distance = double.PositiveInfinity;
        }
        sourceNode.Distance = 0.0d;
        queue.Enqueue(sourceNode);

        while (queue.Count != 0)
        {
            var currentNode = queue.Dequeue();

            if (double.IsPositiveInfinity(currentNode.Distance))
            {
                // All nodes processed --> algorithm finished
                break;
            }

            foreach (var childEdge in graph[currentNode])
            {
                var newDistance = currentNode.Distance + childEdge.Distance;
                if (newDistance < childEdge.Node.Distance)
                {
                    childEdge.Node.Distance = newDistance;
                    childEdge.Node.PreviousNode = currentNode;
                    queue.Enqueue(childEdge.Node);
                }
            }
        }
    }
Esempio n. 23
0
    private static Dictionary<char, string> DijkstraAlgorithm(Node<char> startingNode, HashSet<char> visitedNodes)
    {
        Dictionary<char, string> paths = new Dictionary<char, string>();
        paths[startingNode.Symbol] = startingNode.Symbol.ToString();

        PriorityQueue<Node<char>> queue = new PriorityQueue<Node<char>>();
        startingNode.Weight = 0;
        queue.Enqueue(startingNode);

        while (queue.Count > 0)
        {
            Node<char> currentNode = queue.Dequeue();
            visitedNodes.Add(currentNode.Symbol);
            foreach (var connection in currentNode.Connections)
            {
                Node<char> toNode = connection.ToNode;
                if (!visitedNodes.Contains(toNode.Symbol))
                {
                    long temporaryWeight = currentNode.Weight + connection.Distance;
                    if (temporaryWeight < toNode.Weight)
                    {
                        toNode.Weight = temporaryWeight;
                        queue.Enqueue(toNode);

                        paths[toNode.Symbol] = paths[currentNode.Symbol] + " -> " +
                            toNode.Symbol + "(" + toNode.Weight + ")";
                    }
                }
            }
        }

        return paths;
    }
    public void Test_Dequeue()
    {
        var pq = new PriorityQueue<int>();
        items.ForEach(item => pq.Enqueue(item));

        items.OrderBy(x => x).ToList().ForEach(item => Assert.AreEqual(pq.Dequeue(), item));
    }
Esempio n. 25
0
        public void FifoSamePriority()
        {
            var priorityQueue = new PriorityQueue<object, int>(PriorityQueueType.Minimum);

            var o1 = new object();
            var o2 = new object();
            var o3 = new object();

            priorityQueue.Enqueue(o1);
            priorityQueue.Enqueue(o2);
            priorityQueue.Enqueue(o3);

            Assert.AreSame(o1, priorityQueue.Dequeue());
            Assert.AreSame(o2, priorityQueue.Dequeue());
            Assert.AreSame(o3, priorityQueue.Dequeue());
        }
Esempio n. 26
0
        public void Simple()
        {
            var priorityQueue1 = new PriorityQueue<int, int>(PriorityQueueType.Minimum) { 4 };

            Assert.AreEqual(priorityQueue1.Count, 1);
            Assert.AreEqual(priorityQueue1.Dequeue(), 4);

            priorityQueue1.Add(5);
            priorityQueue1.Add(6, 2);

            Assert.AreEqual(priorityQueue1.Dequeue(), 5);
            Assert.AreEqual(priorityQueue1.Dequeue(), 6);

            priorityQueue1.Add(6, 2);
            priorityQueue1.Add(5);

            Assert.AreEqual(priorityQueue1.Dequeue(), 5);
            Assert.AreEqual(priorityQueue1.Dequeue(), 6);

            var priorityQueue2 = new PriorityQueue<string, int>(PriorityQueueType.Minimum)
                                     {
                                         {"a", 1},
                                         {"b", 2},
                                         {"c", 3},
                                         {"d", 4},
                                         {"e", 5},
                                         {"f", 6},
                                         {"z", 6},
                                         {"y", 5},
                                         {"x", 4},
                                         {"w", 3},
                                         {"v", 2},
                                         {"u", 1},
                                         {"z", 1},
                                         {"y", 2},
                                         {"x", 3},
                                         {"w", 4},
                                         {"v", 5},
                                         {"u", 6}
                                     };

            Assert.AreEqual(priorityQueue2.Count, 18);

            priorityQueue2.Clear();

            Assert.AreEqual(priorityQueue2.Count, 0);
        }
 public void Dequeue_Does_Not_Throw_When_Empty()
 {
     Assert.DoesNotThrow(() =>
     {
         var queue = new PriorityQueue<int>(intComparer);
         Assert.AreEqual(queue.Dequeue(), default(int));
     });
 }
Esempio n. 28
0
    static void Main()
    {
        PriorityQueue<int> myPriorityQueue = new PriorityQueue<int>();
        myPriorityQueue.Enqueue(7);
        myPriorityQueue.Enqueue(17);
        myPriorityQueue.Enqueue(3);
        myPriorityQueue.Enqueue(90);

        myPriorityQueue.Dequeue();

        myPriorityQueue.Enqueue(91);
        myPriorityQueue.Enqueue(53);

        Console.WriteLine(myPriorityQueue.Dequeue());

        myPriorityQueue.Print();
    }
Esempio n. 29
0
        public void PriorityQueueDequeTest()
        {
            PriorityQueue<int> queue = new PriorityQueue<int> ();

            queue.Enqueue (5, 1);
            queue.Enqueue (6, 5);
            queue.Enqueue (6, 5);
            queue.Enqueue (7, 6);
            queue.Enqueue (7, 7);
            queue.Enqueue (7, 2);

            int first = queue.Dequeue ();
            int second = queue.Dequeue ();

            Assert.AreEqual (5, first);
            Assert.AreEqual (7, second);
        }
        static void Main()
        {
            var stringsQueue = new PriorityQueue<string>();

            stringsQueue.Enqueue("Bacho");
            stringsQueue.Enqueue("Boko");
            stringsQueue.Enqueue("Becko");

            var listOfA = new MyList<string>() { "Acho", "Aaaaa" };
            stringsQueue.EnqueueMany(listOfA);

            var first = stringsQueue.Dequeue();
            Console.WriteLine(first); // Aaaaa

            var listOfB = new MyList<string>() { "Bacho", "Boko", "Becko" };
            var listOfC = new MyList<string>() { "Cacho", "Coko", "Cecko" };

            var listsQueue = new PriorityQueue<MyList<string>>();
            listsQueue.Enqueue(listOfA);
            listsQueue.Enqueue(listOfB);
            listsQueue.Enqueue(listOfC);

            var theLongestList = listsQueue.Dequeue();
            Console.WriteLine(theLongestList.Count); //3 - the listOfB
            foreach (var item in theLongestList)
            {
                Console.WriteLine(item);
            }

            theLongestList = listsQueue.Dequeue();
            Console.WriteLine(theLongestList.Count); //3 - the listOfC
            foreach (var item in theLongestList)
            {
                Console.WriteLine(item);
            }

            theLongestList = listsQueue.Dequeue();
            Console.WriteLine(theLongestList.Count); // 2 - the listOfA
            foreach (var item in theLongestList)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine(listsQueue.Count); //0
        }
Esempio n. 31
0
        public static List <Node> Run <Node>
        (
            Node start,
            Func <Node, bool> satisfies,
            Func <Node, List <Tuple <Node, float> > > expand,
            Func <Node, float> heuristic
        )
        {
            //Nodos sin visitar
            var open = new PriorityQueue <Node>();

            //Arranca con el primer nodo
            open.Enqueue(start, 0);

            //Nodos ya visitados
            var closed = new HashSet <Node>();

            //Diccionario de padres, Key: Hijo, Value: Padre
            var parents = new Dictionary <Node, Node>();

            //Diccionarios de costos, Key: Nodo, Value: costo tentativo para llegar
            var costs = new Dictionary <Node, float>();

            costs[start] = 0;

            while (!open.IsEmpty)//Todavia haya nodos para chequear
            {
                var current = open.Dequeue();

                if (satisfies(current))                      //Si el nodo cumple la condicion
                {
                    return(ConstructPath(current, parents)); //Devolvemos el camino a ese nodo
                }

                var currentCost = costs[current];

                //Ponemos al current en el closed asi no lo volvemos a chequear
                closed.Add(current);

                //Para cada hijo del current
                foreach (var childPair in expand(current))
                {
                    var child     = childPair.Item1;
                    var childCost = childPair.Item2;

                    //Si el nodo ya lo habimos procesado lo salteamos
                    if (closed.Contains(child))
                    {
                        continue;
                    }

                    var tentativeCost = currentCost + childCost;
                    if (costs.ContainsKey(child) && tentativeCost > costs[child])
                    {
                        continue;
                    }

                    parents[child] = current;//Le seteamos el padre

                    costs[child] = tentativeCost;
                    open.Enqueue(child, tentativeCost + heuristic(child));//Lo agregamos a la cola
                }
            }

            //Si ningun nodo cumplio la condicion
            return(null);
        }
Esempio n. 32
0
        public void PriorityQueue_DefaultEnqueue_DequeuesItemsCorrectly()
        {
            queue.Enqueue(5);
            queue.Enqueue(10);
            queue.Enqueue(15);
            queue.Enqueue(20);

            Assert.AreEqual(5, queue.Dequeue());
            Assert.AreEqual(10, queue.Dequeue());
            Assert.AreEqual(15, queue.Dequeue());
            Assert.AreEqual(20, queue.Dequeue());
        }
Esempio n. 33
0
        public void Run()
        {
            LogToConsole(@"Flare main loop: start");

            lock (this)
            {
                m_eServiceStatus = FlareServiceStatus.Started;
            }

            try
            {
                m_pqWaitingTargets.Clear();
                m_qTargetsReadyForTesting.Clear();

                ReadTargetsFromDatabase();

                MySqlConnection con = DatabaseConnectionProvider.GetMySqlConnection();

                m_lstAllContacts = Contact.GetAllContacts(con);
                m_dictSystemConfigurationEntries = SystemConfigurationEntry.GetDictionary(con);

                if (m_pqWaitingTargets.IsEmpty())
                {
                    LogToConsole(@"Aborting: The priority queue is empty; there are no servers to monitor.");
                    return;
                }

                // The main loop begins here.
                TimeSpan tsOneSecond  = new TimeSpan(0, 0, 1);
                TimeSpan tsLoopPeriod = new TimeSpan(0, 0, 1);
                bool     bLimitNumberOfMainLoopIterations = (NumberOfMainLoopIterations > 0);

                LogToConsole(@"Starting the main loop...");

                for (int nMainLoopIterationNumber = 0;
                     !bLimitNumberOfMainLoopIterations || nMainLoopIterationNumber < NumberOfMainLoopIterations;
                     ++nMainLoopIterationNumber)
                {
                    DateTime dtNow = DateTime.UtcNow;

                    LogToConsole(string.Format(@"It is now {0}.", dtNow.ToLongTimeString()));

                    if (m_pqWaitingTargets.IsEmpty())
                    {
                        LogToConsole(@"The priority queue is empty; sleeping for one second.");
                        System.Threading.Thread.Sleep(tsOneSecond);
                        continue;
                    }

                    Target targetHead = m_pqWaitingTargets.Peek();

                    LogToConsole(string.Format(@"The target at the head of the queue ('{0}') is due to be tested at {1}.",
                                               targetHead.Name, targetHead.DateTimeOfNextMonitor.ToLongTimeString()));

                    if (dtNow < targetHead.DateTimeOfNextMonitor)
                    {
                        TimeSpan tsDifference      = targetHead.DateTimeOfNextMonitor - dtNow;
                        TimeSpan tsTimeSpanToSleep = (tsDifference < tsLoopPeriod) ? tsDifference : tsLoopPeriod;

                        LogToConsole(string.Format(@"It is not yet time to test the target at the head of the queue.  Sleeping for {0} seconds and {1} milliseconds...",
                                                   tsTimeSpanToSleep.Seconds, tsTimeSpanToSleep.Milliseconds));

                        System.Threading.Thread.Sleep(tsTimeSpanToSleep);
                        continue;
                    }

                    lock (m_qTargetsReadyForTesting)
                    {
                        m_qTargetsReadyForTesting.Enqueue(m_pqWaitingTargets.Dequeue());
                    }

#if MULTITHREAD_TARGET_TESTING
                    // Note: There is also a delegate named ParameterizedThreadStart; perhaps it may be useful
                    // in allowing us to pass a TargetInfo object as a parameter, thus avoiding the m_qTargetsReadyForTesting queue.
                    Thread thread = new Thread(new ThreadStart(ThreadMain_TestTarget));

                    thread.Start();
#else
                    ThreadMain_TestTarget();
#endif

                    lock (this)
                    {
                        if (m_eServiceStatus == FlareServiceStatus.StopRequested)
                        {
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogToConsole(string.Format(@"{0} caught: {1}", ex.GetType().FullName, ex.Message));
            }

            lock (this)
            {
                m_eServiceStatus = FlareServiceStatus.Stopped;
            }

            LogToConsole(@"Flare main loop: end");
        }
Esempio n. 34
0
        public int[][] DecodeNBestCRF(float[] ys, int numStats, int numNBest)
        {
            var vPath          = new PAIR <int, int> [numStats, m_tagSetSize, numNBest];
            var DUMP_LABEL     = -1;
            var vPreAlpha      = new float[m_tagSetSize, numNBest];
            var vAlpha         = new float[m_tagSetSize, numNBest];
            var nStartTagIndex = 0;
            var nEndTagIndex   = 0;
            var MIN_VALUE      = float.MinValue;

            //viterbi algorithm
            for (var i = 0; i < m_tagSetSize; i++)
            {
                for (var j = 0; j < numNBest; j++)
                {
                    vPreAlpha[i, j] = MIN_VALUE;
                    vPath[0, i, j]  = new PAIR <int, int>(DUMP_LABEL, 0);
                }
            }

            vPreAlpha[nStartTagIndex, 0]      = ys[nStartTagIndex];
            vPath[0, nStartTagIndex, 0].first = nStartTagIndex;

            var q = new PriorityQueue <float, PAIR <int, int> >();

            for (var t = 1; t < numStats; t++)
            {
                for (var j = 0; j < m_tagSetSize; j++)
                {
                    while (q.Count() > 0)
                    {
                        q.Dequeue();
                    }

                    var _stp = CRFWeights[j * m_tagSetSize];
                    var _y   = ys[t * m_tagSetSize + j];
                    for (var k = 0; k < numNBest; k++)
                    {
                        var score = vPreAlpha[0, k] + _stp + _y;
                        q.Enqueue(score, new PAIR <int, int>(0, k));
                    }

                    for (var i = 1; i < m_tagSetSize; i++)
                    {
                        _stp = CRFWeights[j * m_tagSetSize + i];
                        for (var k = 0; k < numNBest; k++)
                        {
                            var score = vPreAlpha[i, k] + _stp + _y;
                            if (score <= q.Peek().Key)
                            {
                                break;
                            }

                            q.Dequeue();
                            q.Enqueue(score, new PAIR <int, int>(i, k));
                        }
                    }

                    var idx = numNBest - 1;

                    while (q.Count() > 0)
                    {
                        vAlpha[j, idx]   = q.Peek().Key;
                        vPath[t, j, idx] = q.Peek().Value;
                        idx--;

                        q.Dequeue();
                    }
                }

                vPreAlpha = vAlpha;
                vAlpha    = new float[m_tagSetSize, numNBest];
            }


            //backtrace to get the n-best result path
            var vTagOutput = new int[numNBest][];

            for (var i = 0; i < numNBest; i++)
            {
                vTagOutput[i] = new int[numStats];
            }

            for (var k = 0; k < numNBest; k++)
            {
                vTagOutput[k][numStats - 1] = nEndTagIndex;
                var decision = new PAIR <int, int>(nEndTagIndex, k);

                for (var t = numStats - 2; t >= 0; t--)
                {
                    vTagOutput[k][t] = vPath[t + 1, decision.first, decision.second].first;
                    decision         = vPath[t + 1, decision.first, decision.second];
                }
            }

            return(vTagOutput);
        }
Esempio n. 35
0
        static void Method(string[] args)
        {
            int[] nm = ReadInts();
            int   n  = nm[0];
            int   m  = nm[1];

            int[] pqrs = ReadInts();
            int   p    = pqrs[0];
            int   q    = pqrs[1];
            int   r    = pqrs[2];
            int   s    = pqrs[3];

            int[][] tabcds = new int[m][];
            for (int i = 0; i < m; i++)
            {
                tabcds[i] = ReadInts();
            }

            List <int> xs = new List <int>();
            List <int> ys = new List <int>();

            for (int i = 0; i < m; i++)
            {
                ys.Add(tabcds[i][1]);
                ys.Add(tabcds[i][2]);
                xs.Add(tabcds[i][3]);
                xs.Add(tabcds[i][4]);
            }
            ys.Add(p);
            xs.Add(q);
            ys.Add(r);
            xs.Add(s);
            ys.Sort();
            xs.Sort();
            var        xDict   = new Dictionary <int, int>();
            var        yDict   = new Dictionary <int, int>();
            List <int> plainXs = new List <int>();
            List <int> plainYs = new List <int>();

            for (int i = 0; i < xs.Count; i++)
            {
                if (!xDict.ContainsKey(xs[i]))
                {
                    xDict.Add(xs[i], xDict.Count);
                    plainXs.Add(xs[i]);
                }
                if (!yDict.ContainsKey(ys[i]))
                {
                    yDict.Add(ys[i], yDict.Count);
                    plainYs.Add(ys[i]);
                }
            }
            int[,] yGrid = new int[yDict.Count, xDict.Count];
            int[,] xGrid = new int[yDict.Count, xDict.Count];
            for (int i = 0; i < m; i++)
            {
                int aI = yDict[tabcds[i][1]];
                int bI = yDict[tabcds[i][2]];
                int cI = xDict[tabcds[i][3]];
                int dI = xDict[tabcds[i][4]];
                if (tabcds[i][0] == 1)
                {
                    yGrid[aI, cI]++;
                    yGrid[aI, dI]++;
                    if (bI + 1 < yDict.Count)
                    {
                        yGrid[bI + 1, cI]--;
                        yGrid[bI + 1, dI]--;
                    }
                }
                else
                {
                    xGrid[aI, cI]++;
                    xGrid[bI, cI]++;
                    if (dI + 1 < xDict.Count)
                    {
                        xGrid[aI, dI + 1]--;
                        xGrid[bI, dI + 1]--;
                    }
                }
            }
            int[,] grid = new int[yDict.Count, xDict.Count];
            for (int i = 0; i < yDict.Count; i++)
            {
                for (int j = 0; j < xDict.Count; j++)
                {
                    if (i > 0)
                    {
                        yGrid[i, j] += yGrid[i - 1, j];
                        xGrid[i, j] += xGrid[i - 1, j];
                    }
                    if (j > 0)
                    {
                        yGrid[i, j] += yGrid[i, j - 1];
                        xGrid[i, j] += xGrid[i, j - 1];
                    }
                    grid[i, j] = Min(yGrid[i, j], 1) + Min(xGrid[i, j], 1);
                }
            }

            long[,] distances = new long[yDict.Count, xDict.Count];
            for (int i = 0; i < yDict.Count; i++)
            {
                for (int j = 0; j < xDict.Count; j++)
                {
                    distances[i, j] = long.MaxValue / 2;
                }
            }
            PriorityQueue <int[]> queue = new PriorityQueue <int[]>();

            queue.Enqueue(0, new int[2] {
                yDict[q], xDict[p]
            });
            while (queue.Count > 0)
            {
                var   pair     = queue.Dequeue();
                long  distance = pair.Key;
                int[] pos      = pair.Value;
                if (distances[pos[0], pos[1]] <= distance)
                {
                    continue;
                }

                distances[pos[0], pos[1]] = distance;
                if (pos[0] > 0)
                {
                    long next = distance;
                    //if()
                }
            }
        }
Esempio n. 36
0
        List <PeakNode> DynamicProgramming(List <IPeak> peaks,
                                           Dictionary <double, PeakNode> peak_nodes_map, PriorityQueue <PeakNode> queue)
        {
            List <PeakNode> matched_nodes = new List <PeakNode>();

            while (queue.Count > 0)
            {
                // get node
                PeakNode node = queue.Dequeue();

                // // match peaks
                double     target  = node.Mass();
                List <int> matched = searcher_.Search(target);

                // max if matched a peak
                node.Max(peaks);

                // update matches
                if (matched.Count > 0)
                {
                    node.Add(matched);
                    node.set_miss(0);
                    matched_nodes.Add(node);
                }

                if (node.Missing() > kMissing)
                {
                    continue;
                }

                // extending queue
                Dictionary <string, Dictionary <string, HashSet <int> > > peakMatch = node.Matches();
                foreach (var peptide in peakMatch.Keys.ToList())
                {
                    foreach (var glycan_id in peakMatch[peptide].Keys.ToList())
                    {
                        List <int> peak_indexes = peakMatch[peptide][glycan_id].ToList();

                        IGlycan glycan = glycans_map_[glycan_id];
                        foreach (var g in glycan.Children())
                        {
                            double mass = g.Mass() + util.mass.Peptide.To.Compute(peptide);
                            if (!peak_nodes_map.ContainsKey(mass))
                            {
                                PeakNode next = new PeakNode();
                                // set mass
                                next.set_mass(mass);
                                // set matches
                                next.Add(peptide, g.ID(), peak_indexes);
                                // set missing
                                next.set_miss(node.Missing() + 1);
                                // add node
                                peak_nodes_map[mass] = next;
                                // enqueue
                                queue.Enqueue(mass, peak_nodes_map[mass]);
                            }
                            else
                            {
                                // std::cout << "here" << std::endl;
                                PeakNode next = peak_nodes_map[mass];
                                // set missing
                                next.set_miss(Math.Min(next.Missing(), node.Missing() + 1));
                                // set matches
                                next.Add(peptide, g.ID(), peak_indexes);
                            }
                        }
                    }
                }
            }
            return(matched_nodes);
        }
    public Path FindPath(Node start, Node goal, bool isHierarchicalSearch, bool isJumping, bool isPenalizingDeviations)
    {
        Reset();
        Path path = new Path();

        start.gCost = 0;
        start.hCost = Mathf.Abs(
            Vector3.Distance(start.position, goal.position)
            );
        start.fCost = start.hCost;

        openList.Enqueue(start, start.fCost);

        start.SearchStatus = SearchStatus.OpenList;

        while (!openList.IsEmpty())
        {
            Node bestNode = openList.Dequeue();
            if (bestNode == goal)
            {
                //Construct Path
                Node pathNode = bestNode;
                while (pathNode != start)
                {
                    path.AddPoint(new PathPoint(PathPointType.Node, pathNode, null, pathNode.position));
                    path.AddPoint(new PathPoint(PathPointType.Edge, null, pathNode.edgeOfParent, pathNode.edgeOfParent.Position));
                    //pathNode.GetCell().
                    //Debug.Log(pathNode.position + " Added to path!");
                    pathNode = pathNode.parent;
                }
                path.AddPoint(new PathPoint(PathPointType.Node, start, null, start.position));

                return(path);
            }
            else
            {
                Node neighbor;

                // In Support of Straight Paths
                float     nonStraightPenalty    = 0f;
                bool      isTherePreviousEdge   = false;
                Direction previousEdgeDirection = Direction.None;
                if (isPenalizingDeviations)
                {
                    if (bestNode.edgeOfParent != null)
                    {
                        isTherePreviousEdge   = true;
                        previousEdgeDirection = bestNode.edgeOfParent.DirectionFromNodeOne;
                    }
                    else
                    {
                        isTherePreviousEdge = false;
                    }
                }

                //Debug.Log("BestNode position: " + bestNode.position);
                //Debug.Log("Bestnode # edges= " + bestNode.edges.Count);
                for (int i = 0; i < bestNode.Edges.Count; i++)
                {
                    neighbor = bestNode.Edges[i].OtherNode(bestNode);

                    // In Support of Straight Paths
                    if (isPenalizingDeviations && isTherePreviousEdge)
                    {
                        if (previousEdgeDirection == bestNode.Edges[i].DirectionFromNodeOne)
                        {
                            nonStraightPenalty = 0f;
                        }
                        else
                        {
                            nonStraightPenalty = bestNode.Edges[i].Cost * 0.5f;
                        }
                    }

                    if (isHierarchicalSearch)
                    {
                        if (regionManager.Regions[neighbor.Cell.regionID].SearchStatus != SearchStatus.OnPath)
                        {
                            continue;
                        }
                    }

                    if (neighbor.SearchStatus == SearchStatus.None)
                    {
                        if (bestNode.Edges[i].EdgeType == EdgeType.Elevated)
                        {
                            if (!isJumping) // If jumping is not allowed, maximize the cost of nodes accessed through elevation nodes.
                            {
                                continue;
                                //neighbor.gCost = Mathf.Infinity;
                            }
                            else //If jumping is allowed, simply calcualte costs as normal.
                            {
                                neighbor.gCost = bestNode.gCost + bestNode.Edges[i].Cost;
                            }
                        }
                        else
                        {
                            neighbor.gCost = bestNode.gCost + bestNode.Edges[i].Cost;
                        }

                        neighbor.hCost        = Mathf.Abs(Vector3.Distance(neighbor.position, goal.position)) * heuristicWeight;
                        neighbor.fCost        = neighbor.gCost + neighbor.hCost + nonStraightPenalty;
                        neighbor.parent       = bestNode;
                        neighbor.edgeOfParent = bestNode.Edges[i];

                        openList.Enqueue(neighbor, neighbor.fCost);

                        neighbor.SearchStatus = SearchStatus.OpenList;
                    }
                    else if (neighbor.SearchStatus == SearchStatus.OpenList)
                    {
                        float gCost = bestNode.gCost + bestNode.Edges[i].Cost;
                        float fCost = gCost + neighbor.hCost + nonStraightPenalty;

                        if (fCost < neighbor.fCost)
                        {
                            neighbor.gCost        = gCost;
                            neighbor.fCost        = fCost;
                            neighbor.parent       = bestNode;
                            neighbor.edgeOfParent = bestNode.Edges[i];
                        }
                    }
                    else if (neighbor.SearchStatus == SearchStatus.ClosedList)
                    {
                        continue;
                    }
                }
                closedList.Add(bestNode);
                bestNode.SearchStatus = SearchStatus.ClosedList;
            }
        }

        Debug.LogWarning("Null path has been returned!");
        return(null);
    }
    public RegionPath FindRegionPath(Region start, Region goal, bool isJumping)
    {
        regionManager.ResetAllSearchData();

        /// <summary> Unsearched regions waiting in the priority queue. </summary>
        PriorityQueue <Region> regionOpenList = new PriorityQueue <Region>();
        /// <summary> Fully searched regions. </summary>
        List <Region> closedList = new List <Region>();

        start.gCost = 0;
        start.hCost = Mathf.Abs(
            Vector3.Distance(start.centerPosition, goal.centerPosition)
            );
        start.fCost = start.hCost;

        regionOpenList.Enqueue(start, start.fCost);

        start.SearchStatus = SearchStatus.OpenList;

        while (!regionOpenList.IsEmpty())
        {
            Region bestRegion = regionOpenList.Dequeue();
            if (bestRegion == goal)
            {
                //Construct Path
                RegionPath regionPath   = new RegionPath();
                Region     regionOnPath = bestRegion;
                while (regionOnPath != start)
                {
                    regionPath.AddPoint(new RegionPathPoint(RegionPathPointType.Region, regionOnPath, null, regionOnPath.centerPosition));
                    regionOnPath.SearchStatus = SearchStatus.OnPath;
                    regionPath.AddPoint(new RegionPathPoint(RegionPathPointType.Portal, null, regionOnPath.portalOfParent, regionOnPath.portalOfParent.position));
                    regionOnPath = regionOnPath.parent;
                }
                regionPath.AddPoint(new RegionPathPoint(RegionPathPointType.Region, start, null, start.centerPosition));
                regionOnPath.SearchStatus = SearchStatus.OnPath;

                return(regionPath);
            }
            else
            {
                Region neighbor;

                for (int i = 0; i < bestRegion.portals.Count; i++)
                {
                    neighbor = bestRegion.portals[i].OtherRegion(bestRegion);
                    if (neighbor.SearchStatus == SearchStatus.None)
                    {
                        if (bestRegion.portals[i].EdgeType == EdgeType.Elevated)
                        {
                            if (!isJumping) // If jumping is not allowed, ignore this region and start analyzing the next.
                            {
                                continue;
                            }
                            else // Otherwise, simply calcualte costs as normal.
                            {
                                neighbor.gCost = bestRegion.gCost + bestRegion.portals[i].Cost;
                            }
                        }
                        else
                        {
                            neighbor.gCost = bestRegion.gCost + bestRegion.portals[i].Cost;
                        }

                        neighbor.hCost          = Mathf.Abs(Vector3.Distance(neighbor.centerPosition, goal.centerPosition)) * heuristicWeight;
                        neighbor.fCost          = neighbor.gCost + neighbor.hCost;
                        neighbor.parent         = bestRegion;
                        neighbor.portalOfParent = bestRegion.portals[i];

                        regionOpenList.Enqueue(neighbor, neighbor.fCost);

                        neighbor.SearchStatus = SearchStatus.OpenList;
                    }
                    else if (neighbor.SearchStatus == SearchStatus.OpenList)
                    {
                        float gCost = bestRegion.gCost + bestRegion.portals[i].Cost;
                        float fCost = gCost + neighbor.hCost;

                        if (fCost < neighbor.fCost)
                        {
                            neighbor.gCost          = gCost;
                            neighbor.fCost          = fCost;
                            neighbor.parent         = bestRegion;
                            neighbor.portalOfParent = bestRegion.portals[i];
                        }
                    }
                    else if (neighbor.SearchStatus == SearchStatus.ClosedList)
                    {
                        continue;
                    }
                }
                closedList.Add(bestRegion);
                bestRegion.SearchStatus = SearchStatus.ClosedList;
            }
        }

        return(null);
    }
Esempio n. 39
0
    private int SinkTerrain(
        int landBudget,
        int maximumRegionDensity,
        MapRegionRect region,
        float highRiseProbability,
        int elevationMin,
        int globalWaterLevel,
        float jitterProbability,
        float hexOuterRadius
        )
    {
        int result = landBudget;
        PriorityQueue <Hex> open   = new PriorityQueue <Hex>();
        List <Hex>          closed = new List <Hex>();

        // Get a random hex within the region bounds to be the first hex
        // searched.
        Hex firstHex = GetRandomHex(region);

        open.Enqueue(firstHex, 0);
        CubeVector center        = firstHex.CubeCoordinates;
        int        sink          = Random.value < highRiseProbability ? 2 : 1;
        int        regionDensity = 0;

        while (
            regionDensity < maximumRegionDensity &&
            open.Count > 0
            )
        {
            Hex current = open.Dequeue();
            closed.Add(current);

            int originalElevation = current.elevation;

            int newElevation = current.elevation - sink;

            if (newElevation < elevationMin)
            {
                continue;
            }

            current.SetElevation(
                newElevation,
                hexOuterRadius,
                _hexMap.WrapSize
                );

            if (
                originalElevation >= globalWaterLevel &&
                newElevation < globalWaterLevel
                )
            {
                result++;
            }

            regionDensity += 1;

            List <Hex> neighbors;

            if (_hexMap.TryGetNeighbors(current, out neighbors))
            {
                foreach (Hex neighbor in neighbors)
                {
                    if (closed.Contains(neighbor))
                    {
                        continue;
                    }

                    int priority =
                        CubeVector.WrappedHexTileDistance(
                            neighbor.CubeCoordinates,
                            center,
                            _hexMap.WrapSize
                            ) +
                        Random.value < jitterProbability ? 1 : 0;

                    open.Enqueue(
                        neighbor,
                        priority
                        );
                }
            }
        }

        return(result);
    }
Esempio n. 40
0
        static void Main(string[] args)
        {
            var input = Console.ReadLine();

            var edges   = int.Parse(input);
            var lengths = new double[edges, edges];
            var x_c     = new int[edges];
            var y_c     = new int[edges];

            for (int i = 0; i < edges; i++)
            {
                input = Console.ReadLine();
                var arr = input.Split();
                var x   = int.Parse(arr[0]);
                var y   = int.Parse(arr[1]);

                x_c[i] = x;
                y_c[i] = y;
            }

            for (int i = 0; i < edges; i++)
            {
                for (int j = 0; j < edges; j++)
                {
                    lengths[i, j] = Math.Sqrt(Math.Pow(x_c[i] - x_c[j], 2) + Math.Pow(y_c[i] - y_c[j], 2));
                }
            }
            double s          = 0;
            var    sortedList = new PriorityQueue();
            var    setEdges   = new HashSet <int>();

            setEdges.Add(0);
            for (int i = 1; i < edges; i++)
            {
                var n = new Node();
                n.id     = i;
                n.weight = lengths[0, i];
                sortedList.Enqueue(n);
            }

            for (int i = 1; i < edges; i++)
            {
                Node el;
                while (true)
                {
                    el = sortedList.Dequeue();
                    if (!setEdges.Contains(el.id))
                    {
                        break;
                    }
                }
                setEdges.Add(el.id);
                for (int j = 0; j < edges; j++)
                {
                    var n = new Node();
                    n.id     = j;
                    n.weight = lengths[el.id, j];
                    sortedList.Enqueue(n);
                }
                s += el.weight;
            }

            Console.WriteLine(s);
        }
Esempio n. 41
0
    public AStarPath(GameCube start, GameCube end)
    {
        ConceptualGrid  grid     = GameCubeManager.Instance.Grid;
        List <GameCube> allCubes = grid.AllCubes;

        List <GameCube> closedSet = new List <GameCube> ();

        PriorityQueue <float, GameCube> openSet = new PriorityQueue <float, GameCube> ();

        openSet.Enqueue(0, start);

        //Essentially a linked list
        Dictionary <GameCube, GameCube> path = new Dictionary <GameCube, GameCube> ();

        Dictionary <GameCube, float> g_score = new Dictionary <GameCube, float> ();

        foreach (GameCube h in allCubes)
        {
            g_score [h] = Mathf.Infinity;
        }

        g_score [start] = 0;

        Dictionary <GameCube, float> f_score = new Dictionary <GameCube, float> ();

        foreach (GameCube h in allCubes)
        {
            f_score [h] = Mathf.Infinity;
        }

        f_score [start] = heuristicCostEstimate(start, end);

        while (!openSet.IsEmpty)
        {
            GameCube current = openSet.Dequeue().Value;

            if (current == end)
            {
                RecontructPath(path, current);
                return;
            }

            closedSet.Add(current);

            List <GameCube> neighbours = grid.GetNeighbours(current);

            foreach (GameCube neighbour in neighbours)
            {
                if (neighbour.MoveCost == Mathf.Infinity)
                {
                    continue;
                }

                if (closedSet.Contains(neighbour))
                {
                    continue;
                }


                float tentative_g_score = g_score [current] + current.MoveCost;

                if (openSet.Contains(neighbour) && tentative_g_score >= g_score [neighbour])
                {
                    continue;
                }

                path [neighbour]    = current;
                g_score [neighbour] = tentative_g_score;
                f_score[neighbour]  = g_score [neighbour] + heuristicCostEstimate(neighbour, end);

                if (openSet.Contains(neighbour) == false)
                {
                    openSet.Enqueue(f_score [neighbour], neighbour);
                }
            }
        }

        //if we reach this case, it means all nodes have been closed by final destination wasn't found
        Debug.Log("Path failed");
    }
    public override bool Stroke(Ray ray, BrickTree tree, VoxelMaterial voxelMaterial, VoxelMaterialAtlas materialAtlas, List <byte> blackList, Queue <OctreeEntry <Brick> > outChangedBricks, Bounds bounds)
    {
        // Find the brick intersected
        OctreeEntry <Brick> brickEntry = FirstBrickIntersected(ray, tree, blackList);

        // If we can't find one return
        if (brickEntry == null)
        {
            return(false);
        }

        Brick brick = brickEntry.entry;

        Vector3 brickPosition = brickEntry.bounds.min;

        dummyVector3.Set(brickEntry.cell.x, brickEntry.cell.y, brickEntry.cell.z);
        // Make sure the brick is within the legal paining bounds
        if (!bounds.Contains(dummyVector3))
        {
            // return false;
        }
        // Clear the resused found queue
        found.Clear();
        // Find which cells are intersected within the grid
        selector.Select(ray, brick, brickPosition, blackList, found);

        if (found.Count == 0)
        {
            return(false);
        }

        Vector3i firstIntersection = found.Dequeue();

        Ray offsetRay = new Ray(new Vector3(ray.origin.x - brickPosition.x, ray.origin.y - brickPosition.y, ray.origin.z - brickPosition.z), ray.direction);

        float distance;

        RayEntersCellFromCell(offsetRay, firstIntersection, dummyVector3i, out distance);

        Vector3i adjacentLocal = dummyVector3i;
        Vector3i adjacentWorld = adjacentLocal + brickEntry.bounds.min;

        dummyVector3.Set(adjacentWorld.x, adjacentWorld.y, adjacentWorld.z);
        if (!bounds.Contains(dummyVector3))
        {
            return(false);
        }

        tree.SetVoxelAt(adjacentWorld.x, adjacentWorld.y, adjacentWorld.z, materialAtlas.GetMaterialId(voxelMaterial));

        Vector3i cellModified = new Vector3i(adjacentWorld.x / tree.BrickDimensionX, adjacentWorld.y / tree.BrickDimensionY, adjacentWorld.z / tree.BrickDimensionZ);

        OctreeEntry <Brick> modified = tree.GetAt(cellModified.x, cellModified.y, cellModified.z);

        outChangedBricks.Enqueue(modified);

        if (adjacentLocal.x == 0)
        {
            modified = tree.GetAt(cellModified.x - 1, cellModified.y, cellModified.z);

            outChangedBricks.Enqueue(modified);
        }
        if (adjacentLocal.y == 0)
        {
            modified = tree.GetAt(cellModified.x, cellModified.y - 1, cellModified.z);

            outChangedBricks.Enqueue(modified);
        }
        if (adjacentLocal.z == 0)
        {
            modified = tree.GetAt(cellModified.x, cellModified.y, cellModified.z - 1);

            outChangedBricks.Enqueue(modified);
        }

        return(true);
    }
Esempio n. 43
0
        public override void Solve(IOManager io)
        {
            var largeTowerCount = io.ReadInt();
            var smallTowerCount = io.ReadInt();

            var towers = LoadTowers(io, largeTowerCount + smallTowerCount);

            double minCost = double.MaxValue;

            for (var flag = BitSet.Zero; flag < (1 << smallTowerCount); flag++)
            {
                var uf    = new UnionFind(towers.Length);
                var queue = new PriorityQueue <Bridge>(false);

                for (int i = 0; i < towers.Length; i++)
                {
                    if (i >= largeTowerCount && !flag[i - largeTowerCount])
                    {
                        continue;
                    }

                    for (int j = i + 1; j < towers.Length; j++)
                    {
                        if (j >= largeTowerCount && !flag[j - largeTowerCount])
                        {
                            continue;
                        }

                        var cost = towers[i].GetDistanceFrom(towers[j]);
                        if (towers[i].Color != towers[j].Color)
                        {
                            cost *= 10;
                        }
                        queue.Enqueue(new Bridge(i, j, cost));
                    }
                }

                for (int i = largeTowerCount; i < towers.Length; i++)
                {
                    if (!flag[i - largeTowerCount])
                    {
                        uf.Unite(0, i);
                    }
                }

                double totalCost = 0;

                while (queue.Count > 0)
                {
                    var bridge = queue.Dequeue();

                    if (uf.Unite(bridge.From, bridge.To))
                    {
                        totalCost += bridge.Cost;
                    }
                }

                minCost.ChangeMin(totalCost);
            }

            io.WriteLine(minCost);
        }
Esempio n. 44
0
    public IEnumerable <Node> GetPath(Node start, Node goal)
    {
        bool IsFree(int row, int col)
        {
            return(row >= 0 && row < map.GetLength(0) &&
                   col >= 0 && col < map.GetLength(1) &&
                   (map[row, col] == '-' || map[row, col] == '*'));
        }

        open.Enqueue(start);
        parent[start] = null;
        cost[start]   = 0;

        while (open.Count > 0)
        {
            Node current = open.Dequeue();
            if (goal.Equals(current))
            {
                break;
            }

            void ExecNeighbor(int row, int col)
            {
                if (row == 0 && col == 3)
                {
                    Console.WriteLine(row + " " + col);
                }
                if (!IsFree(row, col))
                {
                    return;
                }

                Node neighbor = new Node(row, col);
                int  newCost  = cost[current] + 1;

                if (cost.ContainsKey(neighbor) && newCost >= cost[neighbor])
                {
                    return;
                }

                cost[neighbor] = newCost;
                neighbor.F     = newCost + GetH(neighbor, goal);
                open.Enqueue(neighbor);
                parent[neighbor] = current;
            }

            ExecNeighbor(current.Row - 1, current.Col);
            ExecNeighbor(current.Row + 1, current.Col);
            ExecNeighbor(current.Row, current.Col - 1);
            ExecNeighbor(current.Row, current.Col + 1);
        }

        if (!parent.ContainsKey(goal))
        {
            return new Node[1] {
                       start
            }
        }
        ;

        Stack <Node> path = new Stack <Node>();

        Node currNode = goal;

        while (currNode != null)
        {
            path.Push(currNode);

            currNode = parent[currNode];
        }

        return(path);
    }
}
Esempio n. 45
0
        public SkeletonNode FindSkeleton()
        {
            SetMovable();

            HashSet <int> unvisitedAreas                = Enumerable.Range(0, BotsCount).ToHashSet();
            Dictionary <Vector, Vector>       dads      = new Dictionary <Vector, Vector>();
            Dictionary <Vector, SkeletonNode> skeletons = new Dictionary <Vector, SkeletonNode>();

            var queue = new PriorityQueue <Vector>();

            queue.Enqueue(0, new Vector(0, 0, 0));
            dads[new Vector(0, 0, 0)] = null;

            while (unvisitedAreas.Count > 0)
            {
                var priority = queue.GetMaxPriority();
                var node     = queue.Dequeue();

                if (VectorComponents.TryGetValue(node, out var component) && unvisitedAreas.Contains(component))
                {
                    unvisitedAreas.Remove(component);

                    var branch = new SkeletonNode
                    {
                        Vector     = node,
                        InputPoint = component
                    };

                    while (dads[branch.Vector] != null)
                    {
                        var dadNode = dads[branch.Vector];
                        var dad     = skeletons.TryGetValue(dadNode, out var dadBranch)
                                                        ? dadBranch
                                                        : new SkeletonNode {
                            Vector = dadNode
                        };
                        dad.Childs[component]    = branch;
                        skeletons[branch.Vector] = branch;
                        skeletons[dad.Vector]    = dad;
                        branch = dad;
                    }
                }

                foreach (var adj in node.GetAdjacents().Where(adj => !dads.ContainsKey(adj) && IsMoveable(adj)))
                {
                    dads[adj] = node;
                    var priorityAdd = (VectorComponents.TryGetValue(adj, out var s) ? s : -1) >= 0 ? -1 : -2;
                    queue.Enqueue(priorityAdd + priority, adj);
                }
            }

            var queue1 = new Queue <SkeletonNode>();

            queue1.Enqueue(skeletons[new Vector(0, 0, 0)]);
            while (queue1.Count > 0)
            {
                var i = queue1.Dequeue();
                if (VectorComponents.ContainsKey(i.Vector))
                {
                    VectorComponents[i.Vector] = Skeleton;
                }

                foreach (var skeletonNode in i.Childs.Select(pair => pair.Value).Distinct())
                {
                    queue1.Enqueue(skeletonNode);
                }
            }


            return(skeletons[new Vector(0, 0, 0)]);
        }
Esempio n. 46
0
        private Position[] AStar(Position fromPosition, Position toPosition, Func <Position, bool> callback)
        {
            Stack <Position> positions = new Stack <Position>();

            HashSet <Position> closed = new HashSet <Position>();

            PriorityQueue <Position, Node> open = new PriorityQueue <Position, Node>(n => n.FromPosition);

            open.Enqueue(new Node(fromPosition, toPosition));

            while (open.Count > 0)
            {
                Node currentNode = open.Dequeue();

                if (currentNode.EstimatedMoves == 0)
                {
                    while (true)
                    {
                        positions.Push(currentNode.FromPosition);

                        if (currentNode.Parent == null)
                        {
                            break;
                        }

                        currentNode = currentNode.Parent;
                    }

                    break;
                }

                closed.Add(currentNode.FromPosition);

                foreach (var moveDirection in new MoveDirection[]
                {
                    MoveDirection.East,
                    MoveDirection.NorthEast,
                    MoveDirection.North,
                    MoveDirection.NorthWest,
                    MoveDirection.West,
                    MoveDirection.SouthWest,
                    MoveDirection.South,
                    MoveDirection.SouthEast
                })
                {
                    Position nextPosition = currentNode.FromPosition.Offset(moveDirection);

                    if (!closed.Contains(nextPosition))
                    {
                        Node nextNode;

                        if (!open.TryGetValue(nextPosition, out nextNode))
                        {
                            if (nextPosition == toPosition || callback(nextPosition))
                            {
                                int moves = currentNode.Moves + Node.CalculateCost(moveDirection);

                                nextNode = new Node(nextPosition, toPosition)
                                {
                                    Parent = currentNode,

                                    Moves = moves
                                };

                                open.Enqueue(nextNode);
                            }
                        }
                        else
                        {
                            int moves = currentNode.Moves + Node.CalculateCost(moveDirection);

                            if (nextNode.Moves > moves)
                            {
                                nextNode.Parent = currentNode;

                                nextNode.Moves = moves;
                            }
                        }
                    }
                }
            }

            return(positions.ToArray());
        }
Esempio n. 47
0
        public ActionResult RecommendCourse()
        {
            if (User.Identity.IsAuthenticated)
            {
                //Taken Courses
                Students user = new StudentsController().QueryStudentID(User.Identity.GetUserId());
                int      Year = (from s in db.Years
                                 select s.Year).Max();
                int Semester = (from s in db.SemesterYear
                                where s.Years.Year == Year
                                select s.SemesterID).Max();

                var taken = from s in db.Registrations
                            where s.StudentID == user.StudentID
                            select s.AvailableCourses.CourseID;
                //Has taken pre-reqs for
                var Aval = from s in db.Prerequisites
                           where taken.Contains(s.RequiredCourseID)
                           select s.CourseID;
                //Remove duplicates part 1
                var RemFalses = from s in db.Prerequisites
                                where !taken.Contains(s.RequiredCourseID)
                                select s.CourseID;
                var ClassWithPreq = from s in db.Prerequisites
                                    select s.CourseID;
                //Remove duplicates part 2
                Aval = from s in Aval
                       where !RemFalses.Contains(s)
                       select s;
                //Availble next Semester
                var nextSemester = from s in db.AvailableCourses
                                   where s.SemesterYear.Years.Year == Year && s.SemesterYear.SemesterID == Semester
                                   select s.CourseID;

                var major = from s in db.MajorRequirements
                            select s;
                //Pull needed class from avalible
                var Recommend = (from s in major
                                 where Aval.Contains(s.CourseID) || (!ClassWithPreq.Contains(s.CourseID) && (!taken.Contains(s.CourseID))) && nextSemester.Contains(s.CourseID)
                                 select s);

                //Sort class based on priority
                var Queue = new PriorityQueue <MajorRequirements>();

                foreach (var item in Recommend)
                {
                    if (item.CoursePriority.PriorityLevel == 1)
                    {
                        Queue.Enqueue(QueuePriorityEnum.Medium, item);
                    }
                    if (item.CoursePriority.PriorityLevel == 2)
                    {
                        Queue.Enqueue(QueuePriorityEnum.Low, item);
                    }
                    if (item.CoursePriority.PriorityLevel == 3)
                    {
                        Queue.Enqueue(QueuePriorityEnum.High, item);
                    }
                }
                List <MajorRequirements> Recommendation = new List <MajorRequirements>();
                try
                {
                    for (int i = 0; i < 6; i++)
                    {
                        Recommendation.Add(Queue.Dequeue());
                    }
                } catch (InvalidOperationException)
                {
                }
                ViewBag.Recommendation = Recommendation;
                return(View());
            }
            else
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
        }
Esempio n. 48
0
    public void help()
    {
        //Debug.Log("HELP!!!");
        if (currentCell.getPassages() > 2)
        {
            MazeCellEdge suggest              = currentCell.GetEdges()[1];
            PriorityQueue <HelperNode> open   = new PriorityQueue <HelperNode>();
            PriorityQueue <HelperNode> closed = new PriorityQueue <HelperNode>();
            open.Enqueue(new HelperNode(currentCell, getDistance(currentCell), 0, getDistance(currentCell), currentCell.GetEdges()[1]));
            bool flag = false;
            while (!flag && !open.isEmpty())
            {
                HelperNode q = open.Dequeue();
                foreach (MazeCellEdge edge in q.getMazeCell().GetEdges())
                {
                    if (edge is MazePassage)
                    {
                        MazeCell     newCell = edge.otherCell;
                        int          g       = q.getG() + 1;
                        int          h       = getDistance(newCell);
                        int          f       = g + h;
                        MazeCellEdge e;
                        if (q.getMazeCell() == currentCell)
                        {
                            e = edge;
                        }
                        else
                        {
                            e = q.getEdge();
                        }
                        if (newCell.getIsWinner())
                        {
                            flag    = true;
                            suggest = e;
                            break;
                        }
                        if (!(open.contains(newCell, f) || closed.contains(newCell, f)))
                        {
                            open.Enqueue(new HelperNode(newCell, f, g, h, e));
                            //Debug.Log("New Node");
                        }
                    }
                }
                closed.Enqueue(new HelperNode(q.getMazeCell(), q.getPriority(), q.getG(), q.getH(), q.getEdge()));
                //Debug.Log("Bye Node");
            }
            //Do fun gui stuff
            Debug.Log(suggest.direction);
            System.Random rng = new System.Random();
            int           helper;
            if (Data.Difficulty == 1)
            {
                helper = 1;
            }
            else if (Data.Difficulty == 2)
            {
                helper = rng.Next(1, 5);
            }
            else
            {
                helper = rng.Next(1, 9);
            }
            string s = "Helper " + helper + " Suggests:\nGo ";
            switch (suggest.direction)
            {
            case MazeDirection.North:
                if (helper == 1 || helper == 5)
                {
                    s += "Up";
                }
                else if (helper == 3 || helper == 7)
                {
                    s += "Down";
                }
                else if (helper == 2 || helper == 8)
                {
                    s += "Right";
                }
                else
                {
                    s += "Left";
                }
                break;

            case MazeDirection.East:
                if (helper == 4 || helper == 8)
                {
                    s += "Up";
                }
                else if (helper == 2 || helper == 6)
                {
                    s += "Down";
                }
                else if (helper == 1 || helper == 7)
                {
                    s += "Right";
                }
                else
                {
                    s += "Left";
                }
                break;

            case MazeDirection.South:
                if (helper == 3 || helper == 7)
                {
                    s += "Up";
                }
                else if (helper == 1 || helper == 5)
                {
                    s += "Down";
                }
                else if (helper == 4 || helper == 6)
                {
                    s += "Right";
                }
                else
                {
                    s += "Left";
                }
                break;

            default:
                if (helper == 2 || helper == 6)
                {
                    s += "Up";
                }
                else if (helper == 4 || helper == 8)
                {
                    s += "Down";
                }
                else if (helper == 3 || helper == 5)
                {
                    s += "Right";
                }
                else
                {
                    s += "Left";
                }
                break;
            }
            text.newDirection(s);
        }
    }
Esempio n. 49
0
#pragma warning disable 612,618
        public static Value.SearchResults <Document> GetDocuments(QueryParser defaultQueryParser, QueryParser customQueryParser, IndexSearcher indexSearcher, string query, DiscoveryType discoveryType, int pageNumber, int pageSize, bool shouldDocumentsBeClustered, string sort, int maximumNumberOfDocumentsToScore)
        {
            Query query2;
            Query wildcardSafeQuery2;

            if (!query.Contains(":"))
            {
                query2             = defaultQueryParser.Parse(query + " AND discoverytype:" + Enum.GetName(typeof(DiscoveryType), discoveryType));
                wildcardSafeQuery2 = defaultQueryParser.Parse(query.Replace("*", " ").Replace("?", " ") + " AND discoverytype:" + Enum.GetName(typeof(DiscoveryType), discoveryType));
            }
            else
            {
                query2             = customQueryParser.Parse(query);
                wildcardSafeQuery2 = customQueryParser.Parse(query.Replace("*", " ").Replace("?", " "));
            }

            TopDocs topDocs = null;

            if (!string.IsNullOrEmpty(sort))
            {
                string[] sorts = sort.ToLower().Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                List <SortField> sortFields = new List <SortField>(sorts.Length / 2);

                for (int i = 0; i < sorts.Length; i++)
                {
                    if (sorts[i].Split(' ')[1] == "asc")
                    {
                        sortFields.Add(new SortField(sorts[i].Split(' ')[0], false));
                    }
                    else
                    {
                        sortFields.Add(new SortField(sorts[i].Split(' ')[0], true));
                    }
                }

                topDocs = indexSearcher.Search(query2, null, maximumNumberOfDocumentsToScore, new Sort(sortFields.ToArray()));
            }
            else
            {
                topDocs = indexSearcher.Search(query2, null, maximumNumberOfDocumentsToScore);
            }

            Value.SearchResults <Document> searchResults = new Value.SearchResults <Document>();

            searchResults.Documents         = new List <Document>();
            searchResults.Query             = query2;
            searchResults.WildcardSafeQuery = wildcardSafeQuery2;

            if (topDocs.scoreDocs.Length != 0)
            {
                Dictionary <string, string> domains = new Dictionary <string, string>();

                PriorityQueue <Document> priorityQueue = new PriorityQueue <Document>();

                //Get the Hits!!!
                //ANODET: Optimize this!!! (Version 2.5+)
                for (int j = 0; j < topDocs.scoreDocs.Length && searchResults.Documents.Count < maximumNumberOfDocumentsToScore && priorityQueue.Count < maximumNumberOfDocumentsToScore; j++)
                {
                    Document document = indexSearcher.Doc(topDocs.scoreDocs[j].doc);

                    float score = topDocs.scoreDocs[j].score;

                    document.Add(new Field("documentid", j.ToString(), Field.Store.YES, Field.Index.NO));
                    document.Add(new Field("relevancyscore", score.ToString(), Field.Store.YES, Field.Index.NO));

                    if (!string.IsNullOrEmpty(sort))
                    {
                        if (shouldDocumentsBeClustered)
                        {
                            if (document.GetField("domain") != null)
                            {
                                string domain = document.GetField("domain").StringValue();

                                if (!domains.ContainsKey(domain))
                                {
                                    domains.Add(domain, null);

                                    if (searchResults.Documents.Count < pageSize && j >= (pageNumber * pageSize) - pageSize)
                                    {
                                        searchResults.Documents.Add(document);
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (searchResults.Documents.Count < pageSize && j >= (pageNumber * pageSize) - pageSize)
                            {
                                searchResults.Documents.Add(document);
                            }
                        }
                    }
                    else
                    {
                        priorityQueue.Enqueue(document, score * (double.Parse(document.GetField("strength").StringValue()) + 1));
                    }
                }

                if (string.IsNullOrEmpty(sort))
                {
                    for (int i = 0; i < topDocs.scoreDocs.Length && priorityQueue.Count != 0; i++)
                    {
                        Document document = priorityQueue.Dequeue();

                        if (shouldDocumentsBeClustered)
                        {
                            if (document.GetField("domain") != null)
                            {
                                string domain = document.GetField("domain").StringValue();

                                if (!domains.ContainsKey(domain))
                                {
                                    domains.Add(domain, null);

                                    if (searchResults.Documents.Count < pageSize && i >= (pageNumber * pageSize) - pageSize)
                                    {
                                        searchResults.Documents.Add(document);
                                    }
                                }
                                else
                                {
                                    i--;
                                }
                            }
                        }
                        else
                        {
                            if (searchResults.Documents.Count < pageSize && i >= (pageNumber * pageSize) - pageSize)
                            {
                                searchResults.Documents.Add(document);
                            }
                        }
                    }
                }

                if (shouldDocumentsBeClustered)
                {
                    searchResults.TotalNumberOfHits = domains.Count;
                }
                else
                {
                    searchResults.TotalNumberOfHits = topDocs.totalHits;
                }
            }

            return(searchResults);
        }
        public void TestEmptyDequeue()
        {
            PriorityQueue <string> q = new PriorityQueue <string>(PriorityQueueType.MaxPriorityQueue);

            q.Dequeue();
        }
Esempio n. 51
0
        public Stack <Point> findPath(Point startPoint, Point endPoint, PathFindController.isAtEnd endPointFunction, GameLocation location, Character character, int limit)
        {
            sbyte[,] array = new sbyte[, ]
            {
                {
                    -1,
                    0
                },
                {
                    1,
                    0
                },
                {
                    0,
                    1
                },
                {
                    0,
                    -1
                }
            };
            PriorityQueue priorityQueue = new PriorityQueue();
            Dictionary <PathNode, PathNode> dictionary = new Dictionary <PathNode, PathNode>();
            int num = 0;

            priorityQueue.Enqueue(new PathNode(startPoint.X, startPoint.Y, 0, null), Math.Abs(endPoint.X - startPoint.X) + Math.Abs(endPoint.Y - startPoint.Y));
            while (!priorityQueue.IsEmpty())
            {
                PathNode pathNode = priorityQueue.Dequeue();
                if (endPointFunction(pathNode, endPoint, location, character))
                {
                    return(PathFindController.reconstructPath(pathNode, dictionary));
                }
                if (!dictionary.ContainsKey(pathNode))
                {
                    dictionary.Add(pathNode, pathNode.parent);
                }
                for (int i = 0; i < 4; i++)
                {
                    PathNode pathNode2 = new PathNode(pathNode.x + (int)array[i, 0], pathNode.y + (int)array[i, 1], pathNode);
                    pathNode2.g = (byte)(pathNode.g + 1);
                    bool colliding = location.isCollidingPosition(new Rectangle(pathNode2.x * Game1.tileSize + 1, pathNode2.y * Game1.tileSize + 1, Game1.tileSize - 2, Game1.tileSize - 2), Game1.viewport, false, 0, false, character, true, false, false);
                    //bool colliding = location.isTilePassable(new Rectangle(pathNode2.x * Game1.tileSize + 1, pathNode2.y * Game1.tileSize + 1, Game1.tileSize - 2, Game1.tileSize - 2), Game1.viewport);
                    //bool colliding = false;
                    if (!dictionary.ContainsKey(pathNode2) &&
                        ((pathNode2.x == endPoint.X && pathNode2.y == endPoint.Y) || (pathNode2.x >= 0 && pathNode2.y >= 0 && pathNode2.x < location.map.Layers[0].LayerWidth && pathNode2.y < location.map.Layers[0].LayerHeight)) &&
                        !colliding)
                    {
                        int priority = (int)pathNode2.g + (Math.Abs(endPoint.X - pathNode2.x) + Math.Abs(endPoint.Y - pathNode2.y));
                        if (!priorityQueue.Contains(pathNode2, priority))
                        {
                            if (!this.DebugPointsSearched.ContainsKey(new Point(pathNode2.x, pathNode2.y)))
                            {
                                this.DebugPointsSearched.Add(new Point(pathNode2.x, pathNode2.y), true);
                            }
                            priorityQueue.Enqueue(pathNode2, priority);
                        }
                    }
                    else if (!this.DebugPointsSearched.ContainsKey(new Point(pathNode2.x, pathNode2.y)))
                    {
                        this.DebugPointsSearched.Add(new Point(pathNode2.x, pathNode2.y), false);
                    }
                }
                num++;
                if (num >= limit)
                {
                    return(null);
                }
            }
            return(null);
        }
        public void TestSequencing()
        {
            PriorityQueue <string> q = GetTestPriorityQueue();

            // z or f
            string str = q.Dequeue();

            Assert.AreEqual(((str == "z") || (str == "f")), true);

            str = q.Dequeue();
            Assert.AreEqual(((str == "z") || (str == "f")), true);

            // y or e
            str = q.Dequeue();
            Assert.AreEqual(((str == "y") || (str == "e")), true);

            str = q.Dequeue();
            Assert.AreEqual(((str == "y") || (str == "e")), true);

            // x or d
            str = q.Dequeue();
            Assert.AreEqual(((str == "x") || (str == "d")), true);

            str = q.Dequeue();
            Assert.AreEqual(((str == "x") || (str == "d")), true);

            // w or c
            str = q.Dequeue();
            Assert.AreEqual(((str == "w") || (str == "c")), true);

            str = q.Dequeue();
            Assert.AreEqual(((str == "w") || (str == "c")), true);

            // v or b
            str = q.Dequeue();
            Assert.AreEqual(((str == "v") || (str == "b")), true);

            str = q.Dequeue();
            Assert.AreEqual(((str == "v") || (str == "b")), true);

            // u or a
            str = q.Dequeue();
            Assert.AreEqual(((str == "u") || (str == "a")), true);

            str = q.Dequeue();
            Assert.AreEqual(((str == "u") || (str == "a")), true);
        }
Esempio n. 53
0
        protected override void ExecuteCore(CarSignalInfo signalInfo)
        {
            if (!IsLoudSpeakerCheck && signalInfo.Sensor.Loudspeaker)
            {
                IsLoudSpeakerCheck = true;
            }

            //过滤10m
            //准备距离0 处理
            if (!isOverPrepareDistance && Settings.OvertakePrepareDistance > 0)
            {
                //超车10米后才评判
                if (signalInfo.Distance - StartDistance < Settings.OvertakePrepareDistance)
                {
                    return;
                }
                if (signalInfo.BearingAngle.IsValidAngle())
                {
                    isOverPrepareDistance = true;
                    StartAngle            = signalInfo.BearingAngle;
                }
                return;
            }

            //TODO:以前有部分客户反馈是会2扣分得。原因不明。不知道是不是信号不稳定影响得。有时间可以打开在多次测试 2018.04.22 鲍君
            if (IsCheckOverSpeed == false && ((Settings.OvertakeSpeedLimit > 0 && signalInfo.SpeedInKmh > Settings.OvertakeSpeedLimit) ||
                                              (Settings.OvertakeLowestSpeed > 0 && signalInfo.SpeedInKmh < Settings.OvertakeLowestSpeed)))
            {
                IsCheckOverSpeed = true;
                CheckRule(true, DeductionRuleCodes.RC30116);
            }

            //达到一次速度
            if (Settings.OvertakeSpeedOnce > 10)
            {
                if (signalInfo.SpeedInKmh > Settings.OvertakeSpeedOnce)
                {
                    _reachSpeedSet.Enqueue(signalInfo.SpeedInKmh);
                }
                if (_reachSpeedSet.Count > 30)
                {
                    _reachSpeedSet.Dequeue();
                }
            }

            //检测是否低于规定速度
            //Logger.InfoFormat("OverTakeTest {0}", OvertakeStepState.ToString());
            //检测开始超车转向角度
            //如果角度大于0
            if (Settings.OvertakeChangeLanesAngle > 0)
            {
                if (OvertakeStepState == OvertakeStep.None)
                {
                    if (signalInfo.BearingAngle.IsValidAngle() &&
                        !GeoHelper.IsBetweenDiffAngle(signalInfo.BearingAngle, StartAngle, Settings.OvertakeChangeLanesAngle))
                    {
                        //设置开始变道时的距离(由于评判转向灯太快,所以延后大概1秒)
                        if (!StartChangingLanesDistance.HasValue)
                        {
                            StartChangingLanesDistance = signalInfo.Distance;
                        }

                        //变道摆正10米后才开始评判
                        //TODO:科目三可以配置的 准备距离
                        if (signalInfo.Distance - StartChangingLanesDistance.Value < Settings.OvertakePrepareDistance)
                        {
                            return;
                        }

                        //设置开始变道时的距离
                        OvertakeStepState = OvertakeStep.StartChangeLanesToLeft;
                        //已经达到了角度认为是在行车道上面
                        isInOverTakeLine = false;
                        //这个应该没问题
                        Logger.DebugFormat("超车时在超车道");
                        if (Settings.OvertakeLightCheck && !IsCheckedOvertakeLeftLight)
                        {
                            IsCheckedOvertakeLeftLight = true;
                            //超车,左转向灯,或者右灯判错
                            if (!CarSignalSet.Query(StartTime).Any(d => d.Sensor.LeftIndicatorLight))
                            {
                                CheckRule(true, DeductionRuleCodes.RC30205, DeductionRuleCodes.SRC3020504);
                            }
                            else
                            {
                                if (!AdvancedSignal.CheckOperationAheadSeconds(x => x.Sensor.LeftIndicatorLight, StartTime, Settings.TurnLightAheadOfTime))
                                {
                                    BreakRule(DeductionRuleCodes.RC30206, DeductionRuleCodes.SRC3020604);
                                }
                            }
                        }

                        //判断一下是否有点客户不需要返回原车道
                    }
                    //TODO:这样写是有问题的
                    //TODO:这个是什么意思?为什么写死了?
                    //else if(signalInfo.Distance - StartDistance > 20)
                    //{
                    //    OvertakeStepState = OvertakeStep.EndChangeLanesToLeft;
                    //    Logger.DebugFormat("超车时在超车道");
                    //}
                }
                else if (OvertakeStepState == OvertakeStep.StartChangeLanesToLeft)
                {
                    //当开始变道后向前行驶15米则认为变道成功
                    if (signalInfo.Distance - StartChangingLanesDistance >= OvertakeChangingLanesSuccessOrBackToOriginalLanceDistance &&
                        signalInfo.BearingAngle.IsValidAngle())
                    {
                        //路径
                        OvertakeStepState     = OvertakeStep.EndChangeLanesToLeft;
                        StartChangeLanesAngle = signalInfo.BearingAngle;

                        //如果设置了不需要返回原车道
                        if (!Settings.OvertakeBackToOriginalLane)
                        {
                            OvertakeStepState = OvertakeStep.EndChangeLanesToRight;
                        }
                        else
                        {
                            IsNeedOvertakeBacked = true;
                            Speaker.PlayAudioAsync(Settings.OvertakeBackToOriginalLaneVocie);
                        }
                    }
                }
                else if (OvertakeStepState == OvertakeStep.EndChangeLanesToLeft)
                {
                    if (signalInfo.BearingAngle.IsValidAngle() && !GeoHelper.IsBetweenDiffAngle(signalInfo.BearingAngle, StartChangeLanesAngle, Settings.OvertakeChangeLanesAngle))
                    {
                        OvertakeStepState = OvertakeStep.EndChangeLanesToRight;
                        if (Settings.OvertakeLightCheck && !IsCheckedOvertakeRightLight)
                        {
                            IsCheckedOvertakeRightLight = true;
                            if (!CarSignalSet.Query(StartTime).Any(d => d.Sensor.RightIndicatorLight))
                            {
                                BreakRule(DeductionRuleCodes.RC30205, DeductionRuleCodes.SRC3020504);
                            }
                            else
                            {
                                if (!AdvancedSignal.CheckOperationAheadSeconds(x => x.Sensor.RightIndicatorLight, StartTime, Settings.TurnLightAheadOfTime))
                                {
                                    BreakRule(DeductionRuleCodes.RC30206, DeductionRuleCodes.SRC3020604);
                                }
                            }
                        }
                    }
                }
                else if (OvertakeStepState == OvertakeStep.EndChangeLanesToRight)
                {
                    //结束考试项目
                    //StopCore();
                    IsSuccess = true;
                    return;
                }
            }
            else
            {
                //表示客户其实只关心打灯问题
                //简单的处理 如果打右转灯之前没有打过左转灯则扣分
                if (signalInfo.Sensor.RightIndicatorLight && !IsCheckedOvertakeLeftLight)
                {
                    //如果没有打左转灯就扣分
                    if (!AdvancedSignal.CheckOperationAheadSeconds(x => x.Sensor.LeftIndicatorLight, StartTime, Settings.TurnLightAheadOfTime))
                    {
                        //CheckRule(true, DeductionRuleCodes.RC30205, DeductionRuleCodes.SRC3020504);
                        if (Settings.OvertakeLightCheck)
                        {
                            BreakRule(DeductionRuleCodes.RC30205, DeductionRuleCodes.SRC3020504);
                        }

                        IsCheckedOvertakeLeftLight = true;
                    }
                }
                //    if (signalInfo.Sensor.RightIndicatorLight)
                //    {
                //        IsCheckedOvertakeLeftLight = true;
                //        CheckRule(tru

                IsSuccess = true;
            }

            base.ExecuteCore(signalInfo);
        }
Esempio n. 54
0
    private bool Search(HexCell fromCell, HexCell toCell, Unit unit)
    {
        int speed = unit.Speed;

        searchFrontierPhase += 2;

        if (searchFrontier == null)
        {
            searchFrontier = new PriorityQueue <HexCell>();
        }
        else
        {
            searchFrontier.Clear();
        }

        fromCell.SearchPhase = searchFrontierPhase;
        fromCell.Distance    = 0;
        searchFrontier.Enqueue(fromCell);
        while (searchFrontier.Count > 0)
        {
            var current = searchFrontier.Dequeue();
            current.SearchPhase += 1;

            if (current == toCell)
            {
                return(true);
            }

            var currentTurn = (current.Distance - 1) / speed;

            for (var dir = HexDirection.NE; dir <= HexDirection.NW; dir++)
            {
                var neighbor = current.GetNeighbor(dir);

                if (neighbor == null || neighbor.SearchPhase > searchFrontierPhase)
                {
                    continue;
                }

                if (neighbor.IsUnderwater || neighbor.Unit)
                {
                    continue;
                }

                if (!unit.IsValidDestination(neighbor))
                {
                    continue;
                }

                var moveCost = unit.GetMoveCost(current, neighbor, dir);
                if (moveCost < 0)
                {
                    continue;
                }

                var distance = current.Distance + moveCost;
                var turn     = (distance - 1) / speed;
                if (turn > currentTurn)
                {
                    distance = turn * speed + moveCost;
                }

                if (neighbor.SearchPhase < searchFrontierPhase)
                {
                    neighbor.SearchPhase     = searchFrontierPhase;
                    neighbor.Distance        = distance;
                    neighbor.PathFrom        = current;
                    neighbor.SearchHeuristic = neighbor.coordinates.DistanceTo(toCell.coordinates);
                    searchFrontier.Enqueue(neighbor);
                }
                else if (distance < neighbor.Distance)
                {
                    var oldPriority = neighbor.Priority;
                    neighbor.Distance = distance;
                    neighbor.PathFrom = current;
                    searchFrontier.Change(neighbor, oldPriority);
                }
            }
        }

        return(false);
    }
Esempio n. 55
0
    public Stack <HexCellBehaviour> FindPath(HexCellBehaviour from, HexCellBehaviour to)
    {
        Stack <HexCellBehaviour>           path = new Stack <HexCellBehaviour>();
        Dictionary <HexCellBehaviour, int> cost = new Dictionary <HexCellBehaviour, int>();
        Dictionary <HexCellBehaviour, HexCellBehaviour> parent = new Dictionary <HexCellBehaviour, HexCellBehaviour>();
        PriorityQueue <HexCellBehaviour> queue = new PriorityQueue <HexCellBehaviour>();
        List <HexCellBehaviour>          unvisitedNeighbours = new List <HexCellBehaviour>();

        cost[from] = 0;
        queue.Enqueue(DistanceBetween(from, to), from);

        bool found = false;

        while (queue.Count > 0 && !found)
        {
            HexCellBehaviour current = queue.Dequeue();
            //Debug.Log("Next node: " + current.cubeCoordinates);
            if (current == to)
            {
                found = true;
                break;
            }

            //find all (unvisited) neighbours
            unvisitedNeighbours.Clear();
            foreach (HexPassable dir in Enum.GetValues(typeof(HexPassable)))
            {
                if (!current.CanGo(dir))
                {
                    continue;
                }
                Vector3 cube = current.cubeCoordinates + cubeNeighboursCoordinates[dir];
                if (IsOutOfBounds(cube))
                {
                    continue;
                }
                HexCellBehaviour neighbour = GetCell(cube);
                if (!cost.ContainsKey(neighbour) || cost[neighbour] > (cost[current] + 1))
                {
                    unvisitedNeighbours.Add(neighbour);
                    cost[neighbour] = cost[current] + current.traverseCost;
                    queue.Enqueue(cost[neighbour] + DistanceBetween(neighbour, to), neighbour);
                    parent[neighbour] = current;
                }
            }
        }

        if (found)
        {
            for (HexCellBehaviour cell = to; cell != from; cell = parent[cell])
            {
                path.Push(cell);
            }
            path.Push(from);
            return(path);
        }
        else
        {
            Debug.LogError("Path not found");
            return(null);
        }
    }
Esempio n. 56
0
    public static void FindPath <NodeType>(
        IGraph <NodeType> graph,
        NodeType startNode,
        NodeType endNode,
        List <NodeType> outputPath,
        int maxiterations = 1000)
    {
        //holds the node that the current node came from
        Dictionary <NodeType, NodeType> parent = new Dictionary <NodeType, NodeType>();

        //generic priority queue, check PriorityQueue.cs
        PriorityQueue <NodeType> priorityQueue = new PriorityQueue <NodeType>();

        HashSet <NodeType> closed = new HashSet <NodeType>();

        priorityQueue.Enqueue(startNode, graph.getDistance(startNode, endNode));

        //the node that we are thinking is a part of the path
        NodeType current;

        for (int i = 0; i < maxiterations; i++)
        {
            if (priorityQueue.Size == 0)
            {
                break;
            }
            else
            {
                //get the node with the lowest weight
                current = priorityQueue.Peek();

                //we are done, now get the path into output
                if (current.Equals(endNode))
                {
                    outputPath.Add(endNode);
                    while (parent.ContainsKey(current))
                    {
                        current = parent[current];
                        outputPath.Add(current);
                    }
                    outputPath.Reverse();
                    break;
                }
                else
                {
                    foreach (var neighbor in graph.Neighbors(current))
                    {
                        //update the neighbors weight
                        float nextWeight = graph.getWeight(neighbor) + priorityQueue.getWeight(current) + graph.getDistance(neighbor, endNode);

                        if (closed.Contains(neighbor))
                        {
                            if (priorityQueue.getWeight(neighbor) > nextWeight)
                            {
                                //if the weight is lower then the prev weight set the best weight
                                priorityQueue.setWeight(neighbor, nextWeight);
                                //update the parent
                                parent[neighbor] = current;
                                continue;
                            }
                            else
                            {
                                continue;
                            }
                        }
                        priorityQueue.Enqueue(neighbor, nextWeight);
                        parent[neighbor] = current;
                    }
                    closed.Add(current);
                    //we are done with the current node, dequeue him from the queue
                    priorityQueue.Dequeue();
                }
            }
        }
    }
Esempio n. 57
0
    public int TrapRainWater(int[][] heightMap)
    {
        int vol = 0;

        // validate input
        int m = heightMap.Length;

        if (m == 0)
        {
            return(vol);
        }
        int n = heightMap[0].Length;

        if (n == 0)
        {
            return(vol);
        }

        PriorityQueue queue = new PriorityQueue();

        bool[,] visited = new bool[m, n];

        // Enqueue the surrounding cells
        for (int i = 0; i < m; i++)
        {
            // first column
            queue.Enqueue(new Point(i, 0, heightMap[i][0]));
            visited[i, 0] = true;
            // last column
            queue.Enqueue(new Point(i, n - 1, heightMap[i][n - 1]));
            visited[i, n - 1] = true;
        }
        for (int j = 1; j < n - 1; j++)
        {
            // first row
            queue.Enqueue(new Point(0, j, heightMap[0][j]));
            visited[0, j] = true;
            // last column
            queue.Enqueue(new Point(m - 1, j, heightMap[m - 1][j]));
            visited[m - 1, j] = true;
        }

        // Console.WriteLine(queue.ToString());

        // BFS
        int tmpX, tmpY, tmpH;

        while (queue.Count() > 0)
        {
            Point currPt = queue.Dequeue();
            // Console.Write("Popped: [{0},{1},{2}], Pushed: ", currPt.x, currPt.y, currPt.h);

            // check left
            tmpX = currPt.x;
            tmpY = currPt.y - 1;
            if (tmpY >= 0 && !visited[tmpX, tmpY])
            {
                tmpH = heightMap[tmpX][tmpY];
                if (tmpH < currPt.h)
                {
                    vol += currPt.h - tmpH;
                    tmpH = currPt.h;
                }
                queue.Enqueue(new Point(tmpX, tmpY, tmpH));
                // Console.Write("[{0},{1},{2}]", tmpX, tmpY, tmpH);
                visited[tmpX, tmpY] = true;
            }
            // check right
            tmpX = currPt.x;
            tmpY = currPt.y + 1;
            if (tmpY < n && !visited[tmpX, tmpY])
            {
                tmpH = heightMap[tmpX][tmpY];
                if (tmpH < currPt.h)
                {
                    vol += currPt.h - tmpH;
                    tmpH = currPt.h;
                }
                queue.Enqueue(new Point(tmpX, tmpY, tmpH));
                // Console.Write("[{0},{1},{2}]", tmpX, tmpY, tmpH);
                visited[tmpX, tmpY] = true;
            }
            // check up
            tmpX = currPt.x - 1;
            tmpY = currPt.y;
            if (tmpX >= 0 && !visited[tmpX, tmpY])
            {
                tmpH = heightMap[tmpX][tmpY];
                if (tmpH < currPt.h)
                {
                    vol += currPt.h - tmpH;
                    tmpH = currPt.h;
                }
                queue.Enqueue(new Point(tmpX, tmpY, tmpH));
                // Console.Write("[{0},{1},{2}]", tmpX, tmpY, tmpH);
                visited[tmpX, tmpY] = true;
            }
            // check down
            tmpX = currPt.x + 1;
            tmpY = currPt.y;
            if (tmpX < m && !visited[tmpX, tmpY])
            {
                tmpH = heightMap[tmpX][tmpY];
                if (tmpH < currPt.h)
                {
                    vol += currPt.h - tmpH;
                    tmpH = currPt.h;
                }
                queue.Enqueue(new Point(tmpX, tmpY, tmpH));
                // Console.Write("[{0},{1},{2}]", tmpX, tmpY, tmpH);
                visited[tmpX, tmpY] = true;
            }
            // Console.WriteLine();
        }
        return(vol);
    }
Esempio n. 58
0
        public void Fitting(Func <CompressedTimeSpan, float> originalCurve, CompressedTimeSpan stepSize, float maxErrorThreshold)
        {
            // Some info: http://wscg.zcu.cz/wscg2008/Papers_2008/full/A23-full.pdf
            // Compression of Temporal Video Data by Catmull-Rom Spline and Quadratic B�zier Curve Fitting
            // And: http://bitsquid.blogspot.jp/2009/11/bitsquid-low-level-animation-system.html

            // Only one or zero keys: no need to do anything.
            if (KeyFrames.Count <= 1)
            {
                return;
            }

            var keyFrames = new LinkedList <KeyFrameData <float> >(this.KeyFrames);
            var evaluator = new Evaluator(keyFrames);

            // Compute initial errors (using Least Square Equation)
            var errors = new LinkedList <ErrorNode>();
            //var errors = new List<float>();
            var errorQueue = new PriorityQueue <LinkedListNode <ErrorNode> >(new ErrorComparer());

            foreach (var keyFrame in keyFrames.EnumerateNodes())
            {
                if (keyFrame.Next == null)
                {
                    break;
                }
                var error     = EvaluateError(originalCurve, evaluator, stepSize, keyFrame.Value, keyFrame.Next.Value);
                var errorNode = errors.AddLast(new ErrorNode(keyFrame, error.Key, error.Value));
                errorQueue.Enqueue(errorNode);
            }
            //for (int keyFrame = 0; keyFrame < KeyFrames.Count - 1; ++keyFrame)
            //{
            //    //errors.Add(EvaluateError(originalCurve, evaluator, stepSize, keyFrame));
            //    var errorNode = errors.AddLast(new ErrorNode(EvaluateError(originalCurve, evaluator, stepSize, keyFrame)));
            //    errorQueue.Enqueue(errorNode);
            //}

            while (true)
            {
                // Already reached enough subdivisions
                var highestError = errorQueue.Dequeue();
                if (highestError.Value.Error <= maxErrorThreshold)
                {
                    break;
                }

                //// Find segment to optimize
                //var biggestErrorIndex = 0;
                //for (int keyFrame = 1; keyFrame < KeyFrames.Count - 1; ++keyFrame)
                //{
                //    if (errors[keyFrame] > errors[biggestErrorIndex])
                //        biggestErrorIndex = keyFrame;
                //}

                //// Already reached enough subdivisions
                //if (errors[biggestErrorIndex] <= maxErrorThreshold)
                //    break;

                // Create new key (use middle point, but better heuristic might improve situation -- like point with biggest error)
                //var middleTime = (start.Value.Time + end.Value.Time) / 2;
                var middleTime = highestError.Value.BiggestDeltaTime;
                //KeyFrames.Insert(biggestErrorIndex + 1, new KeyFrameData<float> { Time = middleTime, Value = originalCurve(middleTime) });
                var newKeyFrame = keyFrames.AddAfter(highestError.Value.KeyFrame, new KeyFrameData <float> {
                    Time = middleTime, Value = originalCurve(middleTime)
                });
                //errors.Insert(biggestErrorIndex + 1, 0.0f);
                var newError = errors.AddAfter(highestError, new ErrorNode(newKeyFrame, CompressedTimeSpan.Zero, 0.0f));

                var highestErrorLastUpdate = newError;
                if (highestErrorLastUpdate.Next != null)
                {
                    highestErrorLastUpdate = highestErrorLastUpdate.Next;
                }

                // Invalidate evaluator (data changed)
                evaluator.InvalidateTime();

                // Update errors
                for (var error = highestError.Previous ?? highestError; error != null; error = error.Next)
                {
                    if (error != highestError && error != newError)
                    {
                        errorQueue.Remove(error);
                    }

                    var errorInfo = EvaluateError(originalCurve, evaluator, stepSize, error.Value.KeyFrame.Value, error.Value.KeyFrame.Next.Value);
                    error.Value.BiggestDeltaTime = errorInfo.Key;
                    error.Value.Error            = errorInfo.Value;

                    errorQueue.Enqueue(error);

                    if (error == highestErrorLastUpdate)
                    {
                        break;
                    }
                }
            }

            KeyFrames = new List <KeyFrameData <float> >(keyFrames);
        }
        public void Dequeue_EmptyQueue_Exception()
        {
            var subject = new PriorityQueue <Priority, int>();

            Assert.Throws <InvalidOperationException>(() => subject.Dequeue());
        }
Esempio n. 60
0
 public static Voxel GetVoxelWithMinimumFScore(PriorityQueue <Voxel> fScore, HashSet <Voxel> openSet)
 {
     return(fScore.Dequeue());
 }