Enqueue() public method

public Enqueue ( string value, int priority ) : void
value string
priority int
return void
        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);
                    }
                }
            }
        }
Beispiel #2
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 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());
        }
Beispiel #4
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);
                }
            }
        }
    }
        public void EnqueueAndDequeueOutOfOrder()
        {
            PriorityQueue queue = new PriorityQueue();
            Assert.False(queue.IsDataAvailable);
            queue.Enqueue(new PriorityQueueEntry(Priority.Pri1));
            queue.Enqueue(new PriorityQueueEntry(Priority.Ping));
            queue.Enqueue(new PriorityQueueEntry(Priority.Pri3));
            Assert.True(queue.IsDataAvailable);

            PriorityQueueEntry output;
            Assert.True(queue.TryDequeue(out output));
            Assert.NotNull(output);
            Assert.Equal(Priority.Ping, output.Priority);
            Assert.True(queue.IsDataAvailable);

            Assert.True(queue.TryDequeue(out output));
            Assert.NotNull(output);
            Assert.Equal(Priority.Pri1, output.Priority);
            Assert.True(queue.IsDataAvailable);

            Assert.True(queue.TryDequeue(out output));
            Assert.NotNull(output);
            Assert.Equal(Priority.Pri3, output.Priority);

            Assert.False(queue.IsDataAvailable);
        }
    //-------------------------------------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;
    }
Beispiel #7
0
        public void SimpleWithPriority()
        {
            var priorityQueue = new PriorityQueue<string, int>(PriorityQueueType.Minimum);

            int priority;

            priorityQueue.Enqueue("g", 6);

            var item = priorityQueue.Peek(out priority);

            Assert.AreEqual(item, "g");
            Assert.AreEqual(priority, 6);
            Assert.AreEqual(priorityQueue.Count, 1);

            priorityQueue.Enqueue("h", 5);

            item = priorityQueue.Peek(out priority);

            Assert.AreEqual(item, "h");
            Assert.AreEqual(priority, 5);
            Assert.AreEqual(priorityQueue.Count, 2);

            priorityQueue.Enqueue("i", 7);

            item = priorityQueue.Peek(out priority);

            Assert.AreEqual(item, "h");
            Assert.AreEqual(priority, 5);
            Assert.AreEqual(priorityQueue.Count, 3);
        }
Beispiel #8
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;
    }
    // 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);
                }
            }
        }
    }
Beispiel #10
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()));
    }
    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);
                }
            }
        }
    }
        public void Count_Returns_Correct_Count()
        {
            var queue = new PriorityQueue<int>(intComparer);
            queue.Enqueue(1);
            queue.Enqueue(2);

            Assert.AreEqual(2, queue.Count);
        }
Beispiel #13
0
    public static List<int> DijkstraAlgorithm(Dictionary<Node, Dictionary<Node, int>> graph, Dictionary<int, Node> nodes, int sourceNode, int destinationNode)
    {
        int[] previous = new int[graph.Count];
        bool[] visited = new bool[graph.Count];
        PriorityQueue<Node> priorityQueue = new PriorityQueue<Node>();
        var startNode = nodes[sourceNode];
        startNode.DistanceFromStart = 100000;

        for (int i = 0; i < previous.Length; i++)
        {
            previous[i] = -1;
        }

        priorityQueue.Enqueue(startNode);

        while (priorityQueue.Count > 0)
        {
            var currentNode = priorityQueue.ExtractMin();

            if (currentNode.Index == destinationNode)
            {
                break;
            }

            foreach (var edge in graph[currentNode])
            {
                if (!visited[edge.Key.Index])
                {
                    priorityQueue.Enqueue(edge.Key);
                    visited[edge.Key.Index] = true;
                }

                var distance = ((double)currentNode.DistanceFromStart / 100000) * ((double)edge.Value / 100000) * 100000;
                if (distance > edge.Key.DistanceFromStart && edge.Key.Index != sourceNode)
                {
                    edge.Key.DistanceFromStart = (int)distance;
                    previous[edge.Key.Index] = currentNode.Index;
                    priorityQueue.DecreaseKey(edge.Key);
                }
            }
        }

        if (previous[destinationNode] == -1)
        {
            return null;
        }

        List<int> path = new List<int>();
        int current = destinationNode;
        while (current != -1)
        {
            path.Add(current);
            current = previous[current];
        }

        path.Reverse();
        return path;
    }
        public void PriorityQueuePeekTest()
        {
            PriorityQueue<int> queue = new PriorityQueue<int> ();

            queue.Enqueue (5, 3);
            queue.Enqueue (6, 2);

            Assert.AreEqual (6, queue.Peek ());
        }
        public void EnqueueTwoElementsTest()
        {
            PriorityQueue<string> queue = new PriorityQueue<string>();

            queue.Enqueue("Pesho");
            queue.Enqueue("Gosho");

            Assert.AreEqual(2, queue.Count);
        }
Beispiel #16
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);
 }
Beispiel #17
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());
        }
        public void WorkPriorityQueue()
        {
            var intPriorityQueue = new PriorityQueue<int>();
            var stringPriorityQueue = new PriorityQueue<string>();
            var userPriorityQueue = new PriorityQueue<User>();

            try
            {
                intPriorityQueue.Enqueue(5, 1);
                intPriorityQueue.Enqueue(40, 1);
                Console.WriteLine("Number of elements of 1st order in queue = {0}", intPriorityQueue.GetCount(1));
                Console.WriteLine("First element of 1st priority = {0}", intPriorityQueue.First());
                Console.WriteLine("Last element of 1st priority = {0}", intPriorityQueue.Last());
                intPriorityQueue.Dequeue();
                intPriorityQueue.Enqueue(671, 2);
                intPriorityQueue.Enqueue(30, 4);
                intPriorityQueue.Enqueue(8932, 4);
                Console.WriteLine("First element of 4th priority = {0}", intPriorityQueue.First(4));
                Console.WriteLine("Last element of 4th priority = {0}", intPriorityQueue.Last(4));
                Console.WriteLine("Queue length = {0}", intPriorityQueue.Count);

                stringPriorityQueue.Enqueue("", 7);
                stringPriorityQueue.Enqueue("40", 7);
                //Console.WriteLine("Number of elements of 1st order in queue = {0}", stringPriorityQueue.GetCount(1));
                Console.WriteLine("First element of 1st priority = {0}", stringPriorityQueue.First());
                Console.WriteLine("Last element of 1st priority = {0}", stringPriorityQueue.Last());
                stringPriorityQueue.Dequeue();
                stringPriorityQueue.Enqueue("thirteen", 4);
                stringPriorityQueue.Enqueue("god", 4);
                Console.WriteLine("First element of 4th priority = {0}", stringPriorityQueue.First(4));
                Console.WriteLine("Last element of 4th priority = {0}", stringPriorityQueue.Last(4));
                Console.WriteLine("Queue length = {0}", stringPriorityQueue.Count);

                userPriorityQueue.Enqueue(new User("Bardara", "Morgrad", new DateTime(1992, 12, 5)), 1);
                userPriorityQueue.Enqueue(new User("Viki", "Crachkovic", new DateTime(1982, 2, 5)), 2);
                Console.WriteLine("Number of elements of 1st order in queue = {0}", userPriorityQueue.GetCount(1));
                Console.WriteLine("First element of 1st priority = {0}", userPriorityQueue.First().FullName);
                Console.WriteLine("Last element of 1st priority = {0}", userPriorityQueue.Last().FullName);
                userPriorityQueue.Dequeue();
                userPriorityQueue.Enqueue(new User("Somalien", "Fred", new DateTime(1976, 12, 5)), 2);
                //Console.WriteLine("First element of 4th priority = {0}", userPriorityQueue.First(4).FullName);
                //Console.WriteLine("Last element of 4th priority = {0}", userPriorityQueue.Last(4).FullName);
                Console.WriteLine("Queue length = {0}", userPriorityQueue.Count);
                MySimpleCollectionTesting();
                StudentDictionaryTesting();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception occured - {0}", e.Message);
            }
            Console.ReadKey();
        }
Beispiel #20
0
        public static void Main()
        {
            PriorityQueue<int> que = new PriorityQueue<int>();
            que.Enqueue(5);
            que.Enqueue(2);
            que.Enqueue(3);
            que.Enqueue(1);

            while (que.Count > 0)
            {
                Console.WriteLine(que.Dequeue());
            }
        }
Beispiel #21
0
        public void Simple()
        {
            var priorityQueue = new PriorityQueue<string, int>(PriorityQueueType.Minimum);

            priorityQueue.Enqueue("g", 6);
            Assert.AreEqual(priorityQueue.Peek(), "g");

            priorityQueue.Enqueue("h", 5);
            Assert.AreEqual(priorityQueue.Peek(), "h");

            priorityQueue.Enqueue("i", 7);
            Assert.AreEqual(priorityQueue.Peek(), "h");
        }
 static void Main()
 {
     var people = new PriorityQueue<Person>();
     people.Enqueue(new Person("Nakov", 25));
     people.Enqueue(new Person("Petya", 24));
     people.Enqueue(new Person("Pesho", 25));
     people.Enqueue(new Person("Maria", 22));
     people.Enqueue(new Person("Ivan", int.MinValue));
     while (people.Count > 0)
     {
         Console.WriteLine(people.Dequeue());
     }
 }
        static void Main()
        {
            PriorityQueue<int> myPriorityQueue = new PriorityQueue<int>();
            for (int i = 0; i < 10; i++)
            {
                if (i != 2)
                {
                    myPriorityQueue.Enqueue(i);
                }
            }

            myPriorityQueue.Enqueue(2);
            myPriorityQueue.Dequeue();
        }
Beispiel #24
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);
        }
Beispiel #25
0
	public AstarResponse GetRouteAstar(int pmStartId, List<int> pmTargets, int heuresticPoint)
	{
		//Queue<int> frontier = new Queue<int>();
		PriorityQueue<int,int> frontier = new PriorityQueue<int, int>();
		frontier.Enqueue (pmStartId, 0);

		Dictionary<int,int> cameFrom = new Dictionary<int, int>(); 
		Dictionary<int,int> costSoFar = new Dictionary<int, int> ();

		costSoFar.Add (pmStartId, 0);

		int foundTarget = 0;


		while (!frontier.Empty()) {
			int current = frontier.Dequeue ();

			if (pmTargets.Contains (current)) {
				foundTarget = current;
				break;
			}

			List<int> neighbours = SelectFromGrid.instance.GetAdjacentNonBlockedFieldsWithDiagonalCheck (current);

			foreach (int next in neighbours) {

				int newCost = costSoFar [current] + this.GetCellMoveCost (next);

				if (!costSoFar.ContainsKey (next) || newCost < costSoFar [next]) {
					costSoFar [next] = newCost + Length (next, heuresticPoint);
					int lvPriority = newCost;

					frontier.Enqueue (next, newCost);

					cameFrom [next] = current;

				}

			}

		}

		Debug.Log ("Reached in " + cameFrom.Count + " moves");

		tab = cameFrom;

		return new AstarResponse (cameFrom, pmStartId, foundTarget);

	}
Beispiel #26
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");
        }
        public void Build(IMap map, MapSettings settings)
        {
            var queue = new PriorityQueue<Corner>((a, b) => -a.DistanceForMoisture.CompareTo(b.DistanceForMoisture));

            foreach (var corner in map.Corners)
            {
                if (corner.IsLake || corner.IsRiver/* || corner.IsOcean*/)
                {
                    queue.Enqueue(corner);
                }
                corner.DistanceForMoisture = corner.IsWater ? 0 : this.m_MaxDist;
            }

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

                foreach (var corner in current.Corners)
                {
                    // TODO: Chack how can it be
                    if (corner != null)
                    {
                        // TODO: improve mechanic
                        double k = corner.Elevation > current.Elevation ? 3 : 1;
                        var newDist = current.DistanceForMoisture + Geometry.Dist(current, corner) * k;
                        if (corner.DistanceForMoisture > newDist)
                        {
                            corner.DistanceForMoisture = newDist;
                            queue.Enqueue(corner);
                        }
                    }
                }
            }

            SetAndNormalizeMoisture(map);

            foreach (var polygon in map.Polygons)
            {
                if (polygon.IsWater)
                {
                    polygon.Moisture = 0;
                }
                else
                {
                    polygon.Moisture = polygon.Corners.Average(c => c.Moisture);
                }
            }
        }
Beispiel #28
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());
        }
Beispiel #29
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));
    }
        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());
        }
Beispiel #31
0
    /// <summary>
    /// Checks if there is a path from fromCell to toCell and how long it takes with the given speed
    /// </summary>
    /// <param name="fromCell">From cell.</param>
    /// <param name="toCell">To cell.</param>
    /// <param name="speed">Speed.</param>
    bool Search(HexCell fromCell, HexCell toCell, int speed)
    {
        searchFrontierPhase += 2;
        if (searchFrontier == null)
        {
            searchFrontier = new PriorityQueue();
        }
        else
        {
            searchFrontier.Clear();
        }

        fromCell.EnableHighlight(Color.white);
        fromCell.SearchPhase = searchFrontierPhase;
        fromCell.Distance    = 0;
        searchFrontier.Enqueue(fromCell);

        while (searchFrontier.Count > 0)
        {
            HexCell current = searchFrontier.Dequeue();

            current.SearchPhase += 1;

            if (current == toCell)
            {
                return(true);
            }
            int currentTurn = (current.Distance - 1) / speed;

            //ef við erum komin yfir það sem við náum á einni umfeðr þá hættum við leit
            if ((current.Distance / speed) > 0)
            {
                break;
            }

            for (HexDirection d = HexDirection.NE; d <= HexDirection.NW; d++)
            {
                HexCell neighbor = current.GetNeighbor(d);
                if (neighbor == null ||
                    neighbor.SearchPhase > searchFrontierPhase)
                {
                    continue;
                }

                if (!neighbor.passable)
                {
                    continue;
                }

                int moveCost = 0;
                // TODO:
                moveCost += neighbor.moveCost;

                int distance = current.Distance + moveCost;
                int turn     = (distance - 1) / speed;

                //eydir movementi sem kall a eftir ef hann er ekki med nog til ad fara a naesta reit
                if (turn > currentTurn)
                {
                    distance = turn * speed + moveCost;
                }
                //ef við erum ekki búnir að skoða þenna reit áður
                if (neighbor.SearchPhase < searchFrontierPhase)
                {
                    neighbor.SearchPhase     = searchFrontierPhase;
                    neighbor.Distance        = distance;
                    neighbor.PathFrom        = current;
                    neighbor.searchHueristic = neighbor.coordinates.DistanceTo(toCell.coordinates);
                    searchFrontier.Enqueue(neighbor);
                }
                else if (distance < neighbor.Distance)
                {
                    int oldPriority = neighbor.SearchPriority;
                    neighbor.Distance = distance;
                    neighbor.PathFrom = current;
                    searchFrontier.Change(neighbor, oldPriority);
                }
            }
        }
        return(false);
    }
Beispiel #32
0
        /// <summary>
        ///     Creates a path from the start voxel to some goal region, returning a list of movements that can
        ///     take a mover from the start voxel to the goal region.
        /// </summary>
        /// <param name="mover">The agent that we want to find a path for.</param>
        /// <param name="startVoxel"></param>
        /// <param name="goal">Goal conditions that the agent is trying to satisfy.</param>
        /// <param name="chunks">The voxels that the agent is moving through</param>
        /// <param name="maxExpansions">Maximum number of voxels to consider before giving up.</param>
        /// <param name="toReturn">The path of movements that the mover should take to reach the goal.</param>
        /// <param name="weight">
        ///     A heuristic weight to apply to the planner. If 1.0, the path is garunteed to be optimal. Higher values
        ///     usually result in faster plans that are suboptimal.
        /// </param>
        /// <param name="continueFunc"></param>
        /// <returns>True if a path could be found, or false otherwise.</returns>
        private static PlanResult Path(CreatureMovement mover, VoxelHandle startVoxel, GoalRegion goal, ChunkManager chunks,
                                       int maxExpansions, ref List <MoveAction> toReturn, float weight, Func <bool> continueFunc)
        {
            // Create a local clone of the octree, using only the objects belonging to the player.
            var         octree        = new OctTreeNode(mover.Creature.World.ChunkManager.Bounds.Min, mover.Creature.World.ChunkManager.Bounds.Max);
            List <Body> playerObjects = new List <Body>(mover.Creature.World.PlayerFaction.OwnedObjects);

            foreach (var obj in playerObjects)
            {
                octree.Add(obj, obj.GetBoundingBox());
            }

            var start = new MoveState()
            {
                Voxel = startVoxel
            };

            var startTime = DwarfTime.Tick();

            if (mover.IsSessile)
            {
                return(new PlanResult()
                {
                    Expansions = 0,
                    Result = PlanResultCode.Invalid,
                    TimeSeconds = DwarfTime.Tock(startTime)
                });
            }

            // Sometimes a goal may not even be achievable a.priori. If this is true, we know there can't be a path
            // which satisifies that goal.
            if (!goal.IsPossible())
            {
                toReturn = null;
                return(new PlanResult()
                {
                    Expansions = 0,
                    Result = PlanResultCode.Invalid,
                    TimeSeconds = DwarfTime.Tock(startTime)
                });
            }

            // Voxels that have already been explored.
            var closedSet = new HashSet <MoveState>();

            // Voxels which should be explored.
            var openSet = new HashSet <MoveState>
            {
                start
            };

            // Dictionary of voxels to the optimal action that got the mover to that voxel.
            var cameFrom = new Dictionary <MoveState, MoveAction>();

            // Optimal score of a voxel based on the path it took to get there.
            var gScore = new Dictionary <MoveState, float>();

            // Expansion priority of voxels.
            var fScore = new PriorityQueue <MoveState>();

            // Starting conditions of the search.
            gScore[start] = 0.0f;
            fScore.Enqueue(start, gScore[start] + weight * goal.Heuristic(start.Voxel));

            // Keep count of the number of expansions we've taken to get to the goal.
            int numExpansions = 0;

            // Check the voxels adjacent to the current voxel as a quick test of adjacency to the goal.
            //var manhattanNeighbors = new List<VoxelHandle>(6);
            //for (int i = 0; i < 6; i++)
            //{
            //    manhattanNeighbors.Add(new VoxelHandle());
            //}

            // Loop until we've either checked every possible voxel, or we've exceeded the maximum number of
            // expansions.
            while (openSet.Count > 0 && numExpansions < maxExpansions)
            {
                if (numExpansions % 10 == 0 && !continueFunc())
                {
                    return new PlanResult
                           {
                               Result      = PlanResultCode.Cancelled,
                               Expansions  = numExpansions,
                               TimeSeconds = DwarfTime.Tock(startTime)
                           }
                }
                ;


                // Check the next voxel to explore.
                var current = GetStateWithMinimumFScore(fScore);
                if (!current.IsValid)
                {
                    // If there wasn't a voxel to explore, just try to expand from
                    // the start again.
                    current = start;

                    numExpansions++;
                }
                if (current.VehicleState.IsRidingVehicle)
                {
                    Console.Out.WriteLine("Yes");
                }
                numExpansions++;

                // If we've reached the goal already, reconstruct the path from the start to the
                // goal.

                /*
                 * if (goal.IsInGoalRegion(current) && cameFrom.ContainsKey(current))
                 * {
                 *  toReturn = ReconstructPath(cameFrom, cameFrom[current]);
                 *  return true;
                 * }
                 */


                //Drawer3D.DrawBox(current.GetBoundingBox(), Color.Red, 0.1f, true);
                // We've already considered the voxel, so add it to the closed set.
                openSet.Remove(current);
                closedSet.Add(current);

                IEnumerable <MoveAction> neighbors = null;

                // Get the voxels that can be moved to from the current voxel.
                neighbors = mover.GetMoveActions(current, octree).ToList();
                //currentChunk.GetNeighborsManhattan(current, manhattanNeighbors);


                var foundGoalAdjacent = neighbors.FirstOrDefault(n => !n.DestinationState.VehicleState.IsRidingVehicle && goal.IsInGoalRegion(n.DestinationState.Voxel));

                // A quick test to see if we're already adjacent to the goal. If we are, assume
                // that we can just walk to it.
                if (foundGoalAdjacent.DestinationState.IsValid && foundGoalAdjacent.SourceState.IsValid)
                {
                    if (cameFrom.ContainsKey(current))
                    {
                        List <MoveAction> subPath = ReconstructPath(cameFrom, foundGoalAdjacent, start);
                        toReturn = subPath;
                        return(new PlanResult()
                        {
                            Result = PlanResultCode.Success,
                            Expansions = numExpansions,
                            TimeSeconds = DwarfTime.Tock(startTime)
                        });
                    }
                }

                // Otherwise, consider all of the neighbors of the current voxel that can be moved to,
                // and determine how to add them to the list of expansions.
                foreach (MoveAction n in neighbors)
                {
                    // If we've already explored that voxel, don't explore it again.
                    if (closedSet.Contains(n.DestinationState))
                    {
                        continue;
                    }

                    // Otherwise, consider the case of moving to that neighbor.
                    float tenativeGScore = gScore[current] + GetDistance(current.Voxel, n.DestinationState.Voxel, n.MoveType, mover);

                    // IF the neighbor can already be reached more efficiently, ignore it.
                    if (openSet.Contains(n.DestinationState) && !(tenativeGScore < gScore[n.DestinationState]))
                    {
                        continue;
                    }

                    // Otherwise, add it to the list of voxels for consideration.
                    openSet.Add(n.DestinationState);

                    // Add an edge to the voxel from the current voxel.
                    var cameAction = n;
                    cameFrom[n.DestinationState] = cameAction;

                    // Update the expansion scores for the next voxel.
                    gScore[n.DestinationState] = tenativeGScore;
                    fScore.Enqueue(n.DestinationState, gScore[n.DestinationState] + weight * (goal.Heuristic(n.DestinationState.Voxel) + (!n.DestinationState.VehicleState.IsRidingVehicle ? 100.0f : 0.0f)));
                }

                // If we've expanded too many voxels, just give up.
                if (numExpansions >= maxExpansions)
                {
                    return(new PlanResult()
                    {
                        Expansions = numExpansions,
                        Result = PlanResultCode.MaxExpansionsReached,
                        TimeSeconds = DwarfTime.Tock(startTime)
                    });
                }
            }

            // Somehow we've reached this code without having found a path. Return false.
            toReturn = null;
            return(new PlanResult()
            {
                Expansions = numExpansions,
                Result = PlanResultCode.NoSolution,
                TimeSeconds = DwarfTime.Tock(startTime)
            });
        }
Beispiel #33
0
        // Find a path from the start to the goal by computing an inverse path from goal to the start. Should only be used
        // if the forward path fails.
        private static PlanResult InversePath(CreatureMovement mover, VoxelHandle startVoxel, GoalRegion goal, ChunkManager chunks,
                                              int maxExpansions, ref List <MoveAction> toReturn, float weight, Func <bool> continueFunc)
        {
            // Create a local clone of the octree, using only the objects belonging to the player.
            var         octree        = new OctTreeNode(mover.Creature.World.ChunkManager.Bounds.Min, mover.Creature.World.ChunkManager.Bounds.Max);
            List <Body> playerObjects = new List <Body>(mover.Creature.World.PlayerFaction.OwnedObjects);

            foreach (var obj in playerObjects)
            {
                octree.Add(obj, obj.GetBoundingBox());
            }

            MoveState start = new MoveState()
            {
                Voxel = startVoxel
            };

            var startTime = DwarfTime.Tick();

            if (mover.IsSessile)
            {
                return(new PlanResult()
                {
                    Result = PlanResultCode.Invalid,
                    Expansions = 0,
                    TimeSeconds = 0
                });
            }

            if (!start.IsValid)
            {
                return(new PlanResult()
                {
                    Result = PlanResultCode.Invalid,
                    Expansions = 0,
                    TimeSeconds = 0
                });
            }


            // Sometimes a goal may not even be achievable a.priori. If this is true, we know there can't be a path
            // which satisifies that goal.
            // It only makes sense to do inverse plans for goals that have an associated voxel.
            if (!goal.IsPossible() || !goal.GetVoxel().IsValid)
            {
                toReturn = null;
                return(new PlanResult()
                {
                    Result = PlanResultCode.Invalid,
                    Expansions = 0,
                    TimeSeconds = 0
                });
            }


            if (goal.IsInGoalRegion(start.Voxel))
            {
                toReturn = new List <MoveAction>();
                return(new PlanResult()
                {
                    Result = PlanResultCode.Success,
                    Expansions = 0,
                    TimeSeconds = 0
                });
            }

            // Voxels that have already been explored.
            var closedSet = new HashSet <MoveState>();

            // Voxels which should be explored.
            var openSet = new HashSet <MoveState>();

            // Dictionary of voxels to the optimal action that got the mover to that voxel.
            var cameFrom = new Dictionary <MoveState, MoveAction>();

            // Optimal score of a voxel based on the path it took to get there.
            var gScore = new Dictionary <MoveState, float>();

            // Expansion priority of voxels.
            var fScore = new PriorityQueue <MoveState>();

            var goalVoxels = new List <VoxelHandle>();

            goalVoxels.Add(goal.GetVoxel());
            // Starting conditions of the search.

            foreach (var goalVoxel in VoxelHelpers.EnumerateCube(goal.GetVoxel().Coordinate)
                     .Select(c => new VoxelHandle(start.Voxel.Chunk.Manager.ChunkData, c)))
            {
                if (!goalVoxel.IsValid)
                {
                    continue;
                }
                var goalState = new MoveState()
                {
                    Voxel = goalVoxel
                };
                if (goal.IsInGoalRegion(goalVoxel))
                {
                    goalVoxels.Add(goalVoxel);
                    openSet.Add(goalState);
                    gScore[goalState] = 0.0f;
                    fScore.Enqueue(goalState,
                                   gScore[goalState] + weight * (goalVoxel.WorldPosition - start.Voxel.WorldPosition).LengthSquared());
                }
            }

            // Keep count of the number of expansions we've taken to get to the goal.
            int numExpansions = 0;

            // Loop until we've either checked every possible voxel, or we've exceeded the maximum number of
            // expansions.
            while (openSet.Count > 0 && numExpansions < maxExpansions)
            {
                if (numExpansions % 10 == 0 && !continueFunc())
                {
                    return new PlanResult
                           {
                               Result      = PlanResultCode.Cancelled,
                               Expansions  = numExpansions,
                               TimeSeconds = DwarfTime.Tock(startTime)
                           }
                }
                ;

                // Check the next voxel to explore.
                var current = GetStateWithMinimumFScore(fScore);
                if (!current.IsValid)
                {
                    continue;
                }
                //Drawer3D.DrawBox(current.GetBoundingBox(), Color.Blue, 0.1f);
                numExpansions++;

                // If we've reached the goal already, reconstruct the path from the start to the
                // goal.
                if (current.Equals(start))
                {
                    toReturn = ReconstructInversePath(goal, cameFrom, cameFrom[start]);
                    return(new PlanResult()
                    {
                        Result = PlanResultCode.Success,
                        Expansions = numExpansions,
                        TimeSeconds = DwarfTime.Tock(startTime)
                    });
                }

                // We've already considered the voxel, so add it to the closed set.
                openSet.Remove(current);
                closedSet.Add(current);

                IEnumerable <MoveAction> neighbors = null;

                // Get the voxels that can be moved to from the current voxel.
                neighbors = mover.GetInverseMoveActions(current, octree);

                // Otherwise, consider all of the neighbors of the current voxel that can be moved to,
                // and determine how to add them to the list of expansions.
                foreach (MoveAction n in neighbors)
                {
                    //Drawer3D.DrawBox(n.SourceVoxel.GetBoundingBox(), Color.Red, 0.1f);
                    // If we've already explored that voxel, don't explore it again.
                    if (closedSet.Contains(n.SourceState))
                    {
                        continue;
                    }

                    // Otherwise, consider the case of moving to that neighbor.
                    float tenativeGScore = gScore[current] + GetDistance(current.Voxel, n.SourceState.Voxel, n.MoveType, mover);

                    // IF the neighbor can already be reached more efficiently, ignore it.
                    if (openSet.Contains(n.SourceState) && gScore.ContainsKey(n.SourceState) && !(tenativeGScore < gScore[n.SourceState]))
                    {
                        continue;
                    }

                    // Otherwise, add it to the list of voxels for consideration.
                    openSet.Add(n.SourceState);

                    // Add an edge to the voxel from the current voxel.
                    var cameAction = n;
                    cameFrom[n.SourceState] = cameAction;

                    // Update the expansion scores for the next voxel.
                    gScore[n.SourceState] = tenativeGScore;
                    fScore.Enqueue(n.SourceState, gScore[n.SourceState] + weight * ((n.SourceState.Voxel.WorldPosition - start.Voxel.WorldPosition).LengthSquared() + (!n.SourceState.VehicleState.IsRidingVehicle ? 100.0f : 0.0f)));
                }

                // If we've expanded too many voxels, just give up.
                if (numExpansions >= maxExpansions)
                {
                    return(new PlanResult()
                    {
                        Result = PlanResultCode.MaxExpansionsReached,
                        Expansions = numExpansions,
                        TimeSeconds = DwarfTime.Tock(startTime)
                    });
                }
            }

            // Somehow we've reached this code without having found a path. Return false.
            toReturn = null;
            return(new PlanResult()
            {
                Result = PlanResultCode.NoSolution,
                Expansions = numExpansions,
                TimeSeconds = DwarfTime.Tock(startTime)
            });
        }
Beispiel #34
0
    static void Solve(IO io)
    {
        var n = io.I;
        var p = io.Is(n);

        var pi = new int[n + 1];

        for (var i = 0; i < n; i++)
        {
            pi[p[i]] = i;
        }

        var evenp  = p.Select((x, i) => i % 2 == 0 ? x : Inf).ToArray();
        var oddp   = p.Select((x, i) => i % 2 != 0 ? x : Inf).ToArray();
        var evenst = new SegmentTree <int>(evenp, Inf, Min);
        var oddst  = new SegmentTree <int>(oddp, Inf, Min);

        var xmin  = Inf;
        var xmini = 0;
        var ymin  = Inf;
        var ymini = n - 1;

        var pq = new PriorityQueue <Pair>();

        pq.Enqueue(new Pair(xmini, ymini, evenst[xmini, ymini]));

        while (pq.Any())
        {
            var pair = pq.Dequeue();

            xmin  = pair.X % 2 == 0 ? evenst[pair.X, pair.Y] : oddst[pair.X, pair.Y];
            xmini = pi[xmin];
            ymin  = pair.X % 2 == 0 ? oddst[xmini + 1, pair.Y] : evenst[xmini + 1, pair.Y];
            ymini = pi[ymin];

            if (xmini > pair.X)
            {
                var tl  = pair.X;
                var tr  = xmini - 1;
                var min = pair.X % 2 == 0 ? evenst[tl, tr] : oddst[tl, tr];

                pq.Enqueue(new Pair(tl, tr, min));
            }

            if (ymini - xmini > 1)
            {
                var tl  = xmini + 1;
                var tr  = ymini - 1;
                var min = pair.X % 2 == 0 ? oddst[tl, tr] : evenst[tl, tr];

                pq.Enqueue(new Pair(tl, tr, min));
            }

            if (ymini < pair.Y)
            {
                var tl  = ymini + 1;
                var tr  = pair.Y;
                var min = pair.X % 2 == 0 ? evenst[tl, tr] : oddst[tl, tr];

                pq.Enqueue(new Pair(tl, tr, min));
            }

            Write(xmin + " " + ymin + " ");
        }
    }
Beispiel #35
0
    public static void FindPath(IMapController map, Vector2Int from, Vector2Int to, ref List <Vector2Int> path, Predicate <Vector2Int> IsValidNavigationTile = null)
    {
        path.Clear();
        if (from == to)
        {
            path.Add(to);
            return;
        }

        Dictionary <Vector2Int, PathInfo> visitedInfo = new Dictionary <Vector2Int, PathInfo>();
        PriorityQueue <Vector2Int>        coordsQueue = new PriorityQueue <Vector2Int>();
        BoundsInt         mapBounds  = map.CellBounds;
        List <Vector2Int> validTiles = new List <Vector2Int>();

        foreach (var position in mapBounds.allPositionsWithin)
        {
            Vector2Int pos2D = (Vector2Int)position;

            if (IsValidNavigationTile == null || !IsValidNavigationTile(pos2D))
            {
                continue;
            }

            validTiles.Add(pos2D);
            visitedInfo[pos2D] = new PathInfo(pos2D);
            coordsQueue.Enqueue(pos2D, visitedInfo[pos2D].Distance);
        }
        visitedInfo[from].Distance = 0;
        coordsQueue.UpdateKey(from, visitedInfo[from].Distance);

        while (coordsQueue.Count > 0)
        {
            Vector2Int   currentCoords = coordsQueue.Dequeue();
            Vector2Int[] deltas;
            map.GetNeighbourDeltas(currentCoords, out deltas);
            PathInfo currentInfo    = visitedInfo[currentCoords];
            int      formerDistance = currentInfo.Distance;
            if (formerDistance == Int32.MaxValue)
            {
                break;
            }
            foreach (var delta in deltas)
            {
                Vector2Int neighbourCoords = currentCoords + delta;
                if (!visitedInfo.ContainsKey(neighbourCoords))
                {
                    continue;
                }

                // TODO: Other checks: Doors, etc, etc.
                PathInfo neighbourInfo = visitedInfo[neighbourCoords];
                int      distance      = formerDistance + 1;
                if (distance < neighbourInfo.Distance)
                {
                    neighbourInfo.From     = currentCoords;
                    neighbourInfo.Distance = distance;

                    int count = coordsQueue.Count;
                    if (coordsQueue.Count > 0)
                    {
                        coordsQueue.UpdateKey(neighbourCoords, distance);
                    }
                    if (count != coordsQueue.Count)
                    {
                        Debug.LogError("Whaaaat");
                    }
                }
            }
        }

        if (visitedInfo.TryGetValue(to, out var destinationInfo) && destinationInfo.Distance != Int32.MaxValue)
        {
            List <Vector2Int> rList = new List <Vector2Int>();
            rList.Add(to);
            while (destinationInfo.From.HasValue)
            {
                rList.Add(destinationInfo.From.Value);
                destinationInfo = visitedInfo[destinationInfo.From.Value];
            }

            for (int i = rList.Count - 1; i >= 0; i--)
            {
                path.Add(rList[i]);
            }
        }
        else
        {
            path.Add(from);
        }
    }
Beispiel #36
0
        static void Method(string[] args)
        {
            int  n            = ReadInt();
            var  upFireQue    = new PriorityQueue <bool>();
            var  downFireQue  = new PriorityQueue <bool>();
            var  upLightQue   = new PriorityQueue <bool>();
            var  downLightQue = new PriorityQueue <bool>();
            int  lightCnt     = 0;
            int  uppedFire    = 0;
            int  uppedLight   = 0;
            var  conds        = new Dictionary <long, bool>();// 強化済みかどうか
            long now          = 0;

            for (int i = 0; i < n; i++)
            {
                int[] vals = ReadInts();
                int   type = vals[0];
                int   val  = vals[1];
                if (type == 0)
                {
                    if (val > 0)
                    {
                        now += val;
                        conds.Add(val, false);
                        downFireQue.Enqueue(-val, true);
                    }
                    else
                    {
                        val *= -1;
                        now -= val;
                        if (conds[val])
                        {
                            now -= val;
                            uppedFire--;
                        }
                        conds.Remove(val);
                    }
                }
                else
                {
                    if (val > 0)
                    {
                        now += val;
                        conds.Add(val, false);
                        downLightQue.Enqueue(-val, true);
                        lightCnt++;
                    }
                    else
                    {
                        val *= -1;
                        now -= val;
                        if (conds[val])
                        {
                            now -= val;
                            uppedLight--;
                        }
                        lightCnt--;
                        conds.Remove(val);
                    }
                }

                while (uppedLight > 0 && uppedLight >= lightCnt)
                {
                    long top = upLightQue.Dequeue().Key;
                    if (conds.ContainsKey(top))
                    {
                        now       -= top;
                        conds[top] = false;
                        uppedLight--;
                        downLightQue.Enqueue(-top, true);
                    }
                }
                while (uppedFire + uppedLight > lightCnt)
                {
                    long top = upFireQue.Dequeue().Key;
                    if (conds.ContainsKey(top))
                    {
                        now       -= top;
                        conds[top] = false;
                        uppedFire--;
                        downFireQue.Enqueue(-top, true);
                    }
                }

                while (uppedFire + uppedLight < lightCnt)
                {
                    while (downFireQue.Count > 0 && !conds.ContainsKey(-downFireQue.Top().Key))
                    {
                        downFireQue.Dequeue();
                    }
                    while (downLightQue.Count > 0 && !conds.ContainsKey(-downLightQue.Top().Key))
                    {
                        downLightQue.Dequeue();
                    }

                    if (downFireQue.Count > 0 && downLightQue.Count > 0)
                    {
                        if (downFireQue.Top().Key < downLightQue.Top().Key &&
                            uppedLight + 1 < lightCnt)
                        {
                            long top = -downLightQue.Dequeue().Key;
                            now       += top;
                            conds[top] = true;
                            uppedLight++;
                            upLightQue.Enqueue(top, true);
                        }
                        else
                        {
                            long top = -downFireQue.Dequeue().Key;
                            now       += top;
                            conds[top] = true;
                            uppedFire++;
                            upFireQue.Enqueue(top, true);
                        }
                    }
                    else if (downFireQue.Count > 0)
                    {
                        long top = -downFireQue.Dequeue().Key;
                        now       += top;
                        conds[top] = true;
                        uppedFire++;
                        upFireQue.Enqueue(top, true);
                    }
                    else if (downLightQue.Count > 0)
                    {
                        if (uppedLight + 1 < lightCnt)
                        {
                            long top = -downLightQue.Dequeue().Key;
                            now       += top;
                            conds[top] = true;
                            uppedLight++;
                            upLightQue.Enqueue(top, true);
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                WriteLine(now);
            }
        }
Beispiel #37
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);
        }
Beispiel #38
0
        private void Tick(DateTime now, TimeSpan elapsed)
        {
            // ignore ticks that come in after we've initialized a shutdown
            if (_shutdown)
            {
                return;
            }

            // check if some timers are ready
            List <KeyValuePair <TaskTimer, TaskEnv> > timers = null;

            System.Threading.Interlocked.Increment(ref _counter);
            _last = now;
            lock (_queue) {
                // dequeue all timers that are ready to go
                while ((_queue.Count > 0) && (_queue.Peek().When <= now))
                {
                    TaskTimer timer = _queue.Dequeue();

                    // check if timer can be transitioned
                    if (timer.TryLockQueued())
                    {
                        // retrieve the associated behavior and reset the timer
                        TaskEnv env = timer.Env;
                        timer.Env = null;
                        timer.SetStatus(TaskTimerStatus.Done);

                        // add timer
                        timers = timers ?? new List <KeyValuePair <TaskTimer, TaskEnv> >();
                        timers.Add(new KeyValuePair <TaskTimer, TaskEnv>(timer, env));
                    }
                }

                // check if a maintance run is due
                if (_maintenance <= now)
                {
                    _maintenance = now.AddSeconds(TaskTimer.QUEUE_RESCAN);
                    DateTime horizon = now.AddSeconds(TaskTimer.QUEUE_CUTOFF);
                    lock (_pending) {
                        List <TaskTimer> activate = new List <TaskTimer>();
                        foreach (TaskTimer timer in _pending.Keys)
                        {
                            if (timer.When <= horizon)
                            {
                                activate.Add(timer);
                            }
                        }
                        foreach (TaskTimer timer in activate)
                        {
                            _pending.Remove(timer);
                            if (timer.TryQueuePending())
                            {
                                _queue.Enqueue(timer);
                            }
                        }
                    }
                }
            }

            // run schedule on its own thread to avoid re-entrancy issues
            if (timers != null)
            {
                foreach (KeyValuePair <TaskTimer, TaskEnv> entry in timers)
                {
                    entry.Key.Execute(entry.Value);
                }
            }
        }
Beispiel #39
0
    // Stop as soon as we reached one target
    public PathInfo[,] AStar(Vector2Int origin, List <Vector2Int> targets)
    {
        PathInfo[,] path = new PathInfo[height, width];
        if (targets.Count == 0)
        {
            return(path);
        }

        targets = targets.ToList();
        targets.Sort((tA, tB) => (tA - origin).sqrMagnitude.CompareTo((tB - origin).sqrMagnitude));
        if (targets.Count > 50)
        {
            targets = targets.Take(50).ToList();
        }
        var roadF = (targets[0] - origin).sqrMagnitude <= 20 * 20 ? roadFactor : 1;

        foreach (Vector2Int target in targets)
        {
            if (!cells[target.y, target.x].isWalkable)
            {
                Debug.LogError("Un-walkable target " + target.ToString());
                return(null);
            }
        }

        PriorityQueue <Position> toVisit = new PriorityQueue <Position>();

        Action <Vector2Int, Vector2Int, float> enqueue = (Vector2Int pos, Vector2Int father, float dOrigin) => {
            float dTarget = Mathf.Infinity;
            foreach (Vector2Int target in targets)
            {
                dTarget = Mathf.Min(dTarget, (target - pos).sqrMagnitude);
            }

            dTarget = Mathf.Sqrt(dTarget) / roadF;
            toVisit.Enqueue(new Position(pos, father, dOrigin, dTarget));
        };

        enqueue(origin, origin, 0);

        while (toVisit.Count() > 0)
        {
            Position c = toVisit.Dequeue();
            if (path[c.pos.y, c.pos.x].visited)
            {
                continue;
            }

            if (visitedOnce != null)
            {
                visitedOnce[c.pos.y, c.pos.x] = true;
            }
            path[c.pos.y, c.pos.x] = new PathInfo(c.father, c.distanceFromOrigin);
            bool done = false;
            foreach (Vector2Int target in targets)
            {
                if (c.pos == target)
                {
                    done = true;
                    break;
                }
            }
            if (done)
            {
                break;
            }
            foreach (Neighbor n in Neighbors(c.pos))
            {
                enqueue(n.pos, c.pos, c.distanceFromOrigin + n.distance / (cells[c.pos.y, c.pos.x].isRoad ? roadF : 1));
            }
        }

        return(path);
    }
Beispiel #40
0
        private List <Grid.Grid.Node> CalculatePath(Grid.Grid grid, Grid.Grid.Node start, Grid.Grid.Node end, bool considerEndCost)
        {
            var path = new List <Grid.Grid.Node>();

            var frontier  = new PriorityQueue <Grid.Grid.Node, int>();
            var cameFrom  = new Dictionary <Grid.Grid.Node, Grid.Grid.Node>();
            var costSoFar = new Dictionary <Grid.Grid.Node, int>();

            frontier.Enqueue(start, 0);
            cameFrom[start]  = start;
            costSoFar[start] = 0;

            while (frontier.Count > 0)
            {
                var current = frontier.Dequeue();

                if (current.Equals(end))
                {
                    var n = end;

                    while (!n.Equals(start))
                    {
                        path.Add(n);
                        n = cameFrom[n];
                    }

                    path.Reverse();
                    return(path);
                }

                var costToCurrent = costSoFar[current];
                foreach (var next in grid.GetNeighbours(current))
                {
                    var cost = costToCurrent;
                    if (next.Equals(end) && !considerEndCost)
                    {
                        cost += 1;
                    }
                    else if (next.Cost < 0)
                    {
                        continue;
                    }
                    else
                    {
                        cost += next.Cost;
                    }

                    if (costSoFar.ContainsKey(next) && cost >= costSoFar[next])
                    {
                        continue;
                    }

                    costSoFar[next] = cost;
                    int priority = cost + Heuristic(next, end);
                    frontier.Enqueue(next, priority);
                    cameFrom[next] = current;
                }
            }

            return(path);
        }
        public IList <int[]> GetSkyline(int[,] buildings)
        {
            int n   = buildings.GetLength(0);
            var rec = new Rectangle[n];
            var cp  = new CriticalPoint[2 * n];

            for (int i = 0, j = 0; i < n; i++, j += 2)
            {
                rec[i]    = new Rectangle(buildings[i, 0], buildings[i, 1], buildings[i, 2], false);
                cp[j]     = new CriticalPoint(buildings[i, 0], rec[i], true);
                cp[j + 1] = new CriticalPoint(buildings[i, 1], rec[i], false);
            }

            Array.Sort(cp);

            List <int[]> skyline = new List <int[]>();
            var          pq      = new PriorityQueue <Rectangle>((x, y) => y.height - x.height);

            for (int i = 0; i < cp.Length; i++)
            {
                do
                {
                    cp[i].rectangle.active = cp[i].start;

                    if (cp[i].start)
                    {
                        pq.Enqueue(cp[i].rectangle);
                    }

                    if (i < cp.Length - 1 && cp[i].point == cp[i + 1].point)
                    {
                        i++;
                    }
                } while (i < cp.Length - 1 && cp[i].point == cp[i + 1].point);

                while (pq.Count > 0 && !pq.Top.active)
                {
                    pq.Dequeue();
                }

                if (pq.Count > 0)
                {
                    if (cp[i].rectangle.end == pq.Top.start)
                    {
                        if (cp[i].rectangle.height != cp[i + 1].rectangle.height)
                        {
                        }
                    }

                    if (cp[i].rectangle.height >= pq.Top.height)
                    {
                        skyline.Add(new int[] { cp[i].point, pq.Top.height });
                    }
                }
                else
                {
                    skyline.Add(new int[] { cp[i].point, 0 });
                }
            }

            return(skyline);
        }
        public string Merge(bool keep_files = false)
        {
            int       memory_per_file = maxMemory / (concurrentFilesCount + 2);
            var       fileQ           = new Queue <string>(files);
            Stopwatch watch           = new Stopwatch();
            long      total_records   = 0;

            while (fileQ.Count > 1)
            {
                watch.Restart();
                var destination_file = new IntermediateFile <InterKey, InterVal>(directory, ID, 2 * memory_per_file);
                var dest             = destination_file.FileStream;

                var current_streams = new List <FileStream>();
                for (int i = 0; i < concurrentFilesCount && fileQ.Count > 0; i++)
                {
                    current_streams.Add(new FileStream(fileQ.Dequeue(), FileMode.Open, FileAccess.Read, FileShare.Read, memory_per_file));
                }

                PriorityQueue <InterKey, Stream> priorityQ = new PriorityQueue <InterKey, Stream>();

                var stream_len = new Dictionary <Stream, long>();

                foreach (var stream in current_streams)
                {
                    stream_len[stream] = stream.Length;
                    if (stream_len[stream] < sizeof(int))
                    {
                        throw new IOException("Malformed intermediate file: The file is too small!");
                    }
                    var key = IntermediateRecord <InterKey, InterVal> .ReadKey(stream);

                    priorityQ.Enqueue(key, stream);
                }

                logger.Debug("Merging {0} files summing to {1} bytes", current_streams.Count, StringFormatter.HumanReadablePostfixs(stream_len.Values.Sum()));

                var  last_key   = priorityQ.Peek().Key;
                bool first_time = true;
                while (priorityQ.Count > 0)
                {
                    total_records++;
                    var best = priorityQ.Dequeue();

                    if (!first_time)
                    {
                        if (last_key.Equals(best.Key))
                        {
                            dest.WriteByte(1);
                        }
                        else
                        {
                            dest.WriteByte(0);
                        }
                    }
                    last_key   = best.Key;
                    first_time = false;

                    destination_file.WriteKey(best.Key);
                    var current_stream = best.Value;
                    var len            = IntermediateRecord <InterKey, InterVal> .ReadValueListLength(current_stream);

                    dest.Write(BitConverter.GetBytes(len), 0, sizeof(int));
                    StreamUtils.Copy(current_stream, dest, len - sizeof(byte));
                    current_stream.ReadByte();

                    if (best.Value.Position >= stream_len[current_stream])
                    {
                        continue;
                    }
                    var new_key = IntermediateRecord <InterKey, InterVal> .ReadKey(current_stream);

                    priorityQ.Enqueue(new_key, current_stream);
                }
                dest.WriteByte(0);
                dest.Close();
                fileQ.Enqueue(destination_file.Path);
                foreach (var stream in current_streams)
                {
                    stream.Close();
                    File.Delete(stream.Name);
                }
                watch.Stop();
                logger.Debug("Merged {0} records to {1} in {2}.", StringFormatter.DigitGrouped(total_records), destination_file.Path, watch.Elapsed);
            }

            return(fileQ.First());
        }
Beispiel #43
0
        static void Method(string[] args)
        {
            int[] nq = ReadInts();
            int   n  = nq[0];
            int   q  = nq[1];

            int[][] abs  = new int[n][];
            var     sets = new HashSet <int> [250000];
            var     ques = new PriorityQueue <int> [250000];

            for (int i = 0; i < 250000; i++)
            {
                sets[i] = new HashSet <int>();
                ques[i] = new PriorityQueue <int>();
            }

            for (int i = 0; i < n; i++)
            {
                abs[i] = ReadInts();
                int a = abs[i][0];
                int b = abs[i][1];
                sets[b].Add(i);
                ques[b].Enqueue(-a, i);
            }

            var maxQue = new PriorityQueue <int>();

            for (int i = 0; i < 250000; i++)
            {
                if (ques[i].Count > 0)
                {
                    maxQue.Enqueue(-ques[i].Top().Key, i);
                }
            }

            for (int i = 0; i < q; i++)
            {
                int[] cd   = ReadInts();
                int   c    = cd[0] - 1;
                int   d    = cd[1];
                int   from = abs[c][1];

                sets[from].Remove(c);
                while (ques[from].Count > 0 &&
                       !sets[from].Contains(ques[from].Top().Value))
                {
                    ques[abs[c][1]].Dequeue();
                }
                if (ques[from].Count > 0)
                {
                    maxQue.Enqueue(-ques[from].Top().Key, from);
                }

                sets[d].Add(c);
                ques[d].Enqueue(-abs[c][0], c);
                maxQue.Enqueue(-ques[d].Top().Key, d);
                abs[c][1] = d;

                while (maxQue.Count > 0 &&
                       (ques[maxQue.Top().Value].Count == 0 ||
                        -ques[maxQue.Top().Value].Top().Key != maxQue.Top().Key))
                {
                    maxQue.Dequeue();
                }

                WriteLine(maxQue.Top().Key);
            }
        }
Beispiel #44
0
    /// <summary>
    /// Finds and returns the points of inaccessability inside a polygon. This is the point where a label is optimally placed.
    /// Implementation from https://github.com/mapbox/polylabel/issues/26
    /// </summary>
    public static float[] GetPolyLabel(float[][][] polygon, float precision = 1f)
    {
        //Find the bounding box of the outer ring
        float minX = 0, minY = 0, maxX = 0, maxY = 0;

        for (int i = 0; i < polygon[0].Length; i++)
        {
            float[] p = polygon[0][i];
            if (i == 0 || p[0] < minX)
            {
                minX = p[0];
            }
            if (i == 0 || p[1] < minY)
            {
                minY = p[1];
            }
            if (i == 0 || p[0] > maxX)
            {
                maxX = p[0];
            }
            if (i == 0 || p[1] > maxY)
            {
                maxY = p[1];
            }
        }

        float width    = maxX - minX;
        float height   = maxY - minY;
        float cellSize = Math.Min(width, height);
        float h        = cellSize / 2;

        //A priority queue of cells in order of their "potential" (max distance to polygon)
        PriorityQueue <float, Cell> cellQueue = new PriorityQueue <float, Cell>();

        if (FloatEquals(cellSize, 0))
        {
            return new[] { minX, minY }
        }
        ;

        //Cover polygon with initial cells
        for (float x = minX; x < maxX; x += cellSize)
        {
            for (float y = minY; y < maxY; y += cellSize)
            {
                Cell cell = new Cell(x + h, y + h, h, polygon);
                cellQueue.Enqueue(cell.Max, cell);
            }
        }

        //Take centroid as the first best guess
        Cell bestCell = GetCentroidCell(polygon);

        //Special case for rectangular polygons
        Cell bboxCell = new Cell(minX + width / 2, minY + height / 2, 0, polygon);

        if (bboxCell.D > bestCell.D)
        {
            bestCell = bboxCell;
        }

        int numProbes = cellQueue.Count;

        while (cellQueue.Count > 0)
        {
            //Pick the most promising cell from the queue
            Cell cell = cellQueue.Dequeue();

            //Update the best cell if we found a better one
            if (cell.D > bestCell.D)
            {
                bestCell = cell;
            }

            //Do not drill down further if there's no chance of a better solution
            if (cell.Max - bestCell.D <= precision)
            {
                continue;
            }

            //Split the cell into four cells
            h = cell.H / 2;
            Cell cell1 = new Cell(cell.X - h, cell.Y - h, h, polygon);
            cellQueue.Enqueue(cell1.Max, cell1);
            Cell cell2 = new Cell(cell.X + h, cell.Y - h, h, polygon);
            cellQueue.Enqueue(cell2.Max, cell2);
            Cell cell3 = new Cell(cell.X - h, cell.Y + h, h, polygon);
            cellQueue.Enqueue(cell3.Max, cell3);
            Cell cell4 = new Cell(cell.X + h, cell.Y + h, h, polygon);
            cellQueue.Enqueue(cell4.Max, cell4);
            numProbes += 4;
        }

        return(new[] { bestCell.X, bestCell.Y });
    }
    public static List <int> DijkstraAlgorithm(Dictionary <Node, Dictionary <Node, int> > graph, Node sourceNode, Node destinationNode)
    {
        int?[] previous = new int?[graph.Count];
        bool[] visited  = new bool[graph.Count];

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

        foreach (var pair in graph)
        {
            pair.Key.DistanceFromStart = double.PositiveInfinity;
        }

        sourceNode.DistanceFromStart = 0;
        priorityQueue.Enqueue(sourceNode);

        while (priorityQueue.Count > 0)
        {
            var currentNode = priorityQueue.ExtractMin();

            if (currentNode == destinationNode)
            {
                break;
            }

            foreach (var edge in graph[currentNode])
            {
                if (!visited[edge.Key.Id])
                {
                    priorityQueue.Enqueue(edge.Key);
                    visited[edge.Key.Id] = true;
                }

                double distance = currentNode.DistanceFromStart + edge.Value;

                if (distance < edge.Key.DistanceFromStart)
                {
                    edge.Key.DistanceFromStart = distance;
                    previous[edge.Key.Id]      = currentNode.Id;
                    priorityQueue.DecreaseKey(edge.Key);
                }
            }
        }

        if (double.IsInfinity(destinationNode.DistanceFromStart))
        {
            return(null);
        }

        List <int> path    = new List <int>();
        int?       current = destinationNode.Id;

        while (current != null)
        {
            path.Add(current.Value);
            current = previous[current.Value];
        }

        path.Reverse();

        return(path);
    }
Beispiel #46
0
    /// <summary>
    /// A star pathfinding to determine shortest path from start to goal
    /// </summary>
    public static List <Tile> AStarPathfinding(Tile startTile, Tile goal, CollisionCheckEnum colCheck)
    {
        //info of where this tile comes from other tile
        Dictionary <Tile, Tile> cameFrom = new Dictionary <Tile, Tile>();
        //info of total cost in certain tile
        Dictionary <Tile, float> totalCost = new Dictionary <Tile, float>();

        //list all the target tile that will be explored
        PriorityQueue <Tile> targets = new PriorityQueue <Tile>();

        targets.Enqueue(0, startTile);

        cameFrom.Add(startTile, null);
        totalCost.Add(startTile, 0);

        while (targets.Count > 0)
        {
            Tile current = targets.Dequeue();             //get the best tile

            if (current == goal)
            {
                break;                 //if reaches goal already
            }

            foreach (Tile neighbour in current.neighbours)
            {
                if (GameMaster.instance.IsTileOccupied(neighbour, colCheck))                 //if next tile is occupied, skip
                {
                    continue;
                }

                //add the total cost with next tile cost
                float newCost = totalCost[current] + neighbour.cost;
                //if neighbour is diagonal to current, add a little cost so they prefer straight line rather than diagonal
                if (current.DiagonalTo(neighbour))
                {
                    newCost += 0.01f;
                }
                //if the neighbour is unexplored OR(then) if the new cost is cheaper than other path
                if (!totalCost.ContainsKey(neighbour) || newCost < totalCost[neighbour])
                {                       //replace it
                    totalCost[neighbour] = newCost;
                    //priority based on cost of movement and total distance
                    // !!!!!
                    // 2016-10-09 I think this is wrong, there is no distance to goal counted...
                    float priority = newCost + current.DistanceToTile(neighbour);
                    //register the next tile based on the priority
                    targets.Enqueue(priority, neighbour);

                    //register current tile as previous tile before next tile
                    if (cameFrom.ContainsKey(neighbour))
                    {
                        cameFrom[neighbour] = current;
                    }
                    else
                    {
                        cameFrom.Add(neighbour, current);
                    }
                }
            }
        }

        List <Tile> results = new List <Tile>();
        Tile        curr    = goal;

        //return results until start point
        while (curr != null)
        {
            results.Add(curr);              //add current tile

            if (cameFrom.ContainsKey(curr))
            {
                curr = cameFrom[curr];                 //next tile is previous tile
            }
            else
            {
                break;
            }
        }
        results.Reverse();         //reverse it
        return(results);
    }
Beispiel #47
0
        /// <summary>
        /// Get an ordered list of all required input variables and  temp variables (i.e. intermediate computations)
        /// necessary for this computed variable's RHS computation in whole the code block
        /// </summary>
        /// <returns></returns>
        internal IEnumerable <IGMacCbRhsVariable> GetUsedVariables()
        {
            //The final list containing the ordered temp variables
            var finalVarsList = new Dictionary <string, IGMacCbRhsVariable>();

            //Get the variables used in the RHS expression of this computed variable
            var rhsVarsList = RhsVariables.Distinct();

            var queue = new PriorityQueue <int, GMacCbTempVariable>();

            //Add the temp variables in a priority queue according to their computation order in the
            //code block
            foreach (var rhsVar in rhsVarsList)
            {
                var rhsTempVar = rhsVar as GMacCbTempVariable;

                if (ReferenceEquals(rhsTempVar, null) == false)
                {
                    queue.Enqueue(-rhsTempVar.ComputationOrder, rhsTempVar);
                    continue;
                }

                finalVarsList.Add(rhsVar.LowLevelName, rhsVar);
            }


            while (queue.Count > 0)
            {
                //Get the next temp variable from the queue
                var tempVar = queue.Dequeue().Value;

                //If the temp variable already exists in the final list do nothing
                if (finalVarsList.ContainsKey(tempVar.LowLevelName))
                {
                    continue;
                }

                //Add tempVar to the final list
                finalVarsList.Add(tempVar.LowLevelName, tempVar);

                //Create a list of variables in the RHS of tempVar's expression but not yet
                //present in the final list
                rhsVarsList =
                    tempVar
                    .RhsVariables
                    .Distinct()
                    .Where(
                        item =>
                        finalVarsList.ContainsKey(item.LowLevelName) == false
                        );

                //Add the temp variables in the list to the priority queue and the inputs variables to
                //the final result
                foreach (var rhsVar in rhsVarsList)
                {
                    var rhsTempVar = rhsVar as GMacCbTempVariable;

                    if (ReferenceEquals(rhsTempVar, null) == false)
                    {
                        queue.Enqueue(-rhsTempVar.ComputationOrder, rhsTempVar);
                        continue;
                    }

                    finalVarsList.Add(rhsVar.LowLevelName, rhsVar);
                }
            }

            //Return the final list after reversing so that the ordering of computations is correct
            return
                (finalVarsList
                 .Select(pair => pair.Value)
                 .Reverse());
        }
Beispiel #48
0
    public LinkedList <Vector2> GetPath(Vector2 start, Vector2 destination)
#endif
    {
        Hex startHex       = GridHelper.Vector2ToHex(start, NavMap.MapLayout);
        Hex destinationHex = GridHelper.Vector2ToHex(destination, NavMap.MapLayout);

        Dictionary <Hex, Hex> came_from = new Dictionary <Hex, Hex>();

#if UNITY_EDITOR
        testedHex = new List <Hex>();
#endif
        if (!BlockedHex.Contains(destinationHex))
        {
            PriorityQueue <float, Hex> frontier = new PriorityQueue <float, Hex>();
            frontier.Enqueue(0, startHex);
            Dictionary <Hex, int> cost_so_far = new Dictionary <Hex, int>();

            came_from[startHex]   = startHex;
            cost_so_far[startHex] = 0;
            while (!frontier.IsEmpty)
            {
                Hex current = frontier.Dequeue();
#if UNITY_EDITOR
                testedHex.Add(current);
#endif
                if (Hex.Equals(current, destinationHex))
                {
                    break;
                }

                for (int i = 0; i < HEX_NUM_SIDES; i++)
                {
                    Hex next = Hex.Neighbor(current, i);
                    if (BlockedHex.Contains(next))
                    {
                        continue;
                    }
                    int new_cost = cost_so_far[current] + UNBLOCKED_HEX_COST;

                    if ((!cost_so_far.ContainsKey(next)) || (new_cost < cost_so_far[next]))
                    {
                        cost_so_far[next] = new_cost;
                        float priority = new_cost + CalculateHeuristic(destinationHex, next);
                        frontier.Enqueue(priority, next);

                        came_from[next] = current;
                    }
                }
            }
        }

        LinkedList <Vector2> path = null;
        if (came_from.Count > 0)
        {
            path = new LinkedList <Vector2>();
#if UNITY_EDITOR
            hexInPath = new List <Hex>();
#endif
            Hex currentHex = destinationHex;
            while (!came_from[currentHex].Equals(startHex))
            {
#if UNITY_EDITOR
                hexInPath.Add(currentHex);
#endif
                path.AddFirst(GridHelper.HexToVector2(currentHex, NavMap.MapLayout));
                currentHex = came_from[currentHex];
            }

            path.AddFirst(start);
            SmoothPath(path);
        }

        return(path);
    }
Beispiel #49
0
        /// <summary>
        /// A* search algorithm from one node to another.
        /// </summary>
        /// <typeparam name="T">Node type</typeparam>
        /// <param name="fromNode">Starting node</param>
        /// <param name="toNode">Goal node</param>
        /// <param name="heuristicFunc">Heuristic cost function for a node</param>
        /// <param name="costFunc">Real cost function for moving from one node to neighbouring node</param>
        /// <param name="neighboursFunc">Node neighbours</param>
        /// <returns>Nodes in the path</returns>
        public static IEnumerable <Move <T> > AStar <T>(T fromNode, T toNode, Func <T, double> heuristicFunc, Func <T, T, double> costFunc, Func <T, IEnumerable <T> > neighboursFunc)
        {
            if (heuristicFunc == null)
            {
                throw new ArgumentNullException(nameof(heuristicFunc));
            }
            if (costFunc == null)
            {
                throw new ArgumentNullException(nameof(costFunc));
            }
            if (neighboursFunc == null)
            {
                throw new ArgumentNullException(nameof(neighboursFunc));
            }

            if (fromNode.Equals(toNode))
            {
                return(new Move <T> [0]);
            }

            var cameFrom  = new Dictionary <T, T>();
            var closedSet = new HashSet <T>();
            var openSet   = new PriorityQueue <T>();
            var nodeScore = new Dictionary <T, double> {
                [fromNode] = 0
            };

            openSet.Enqueue(fromNode, heuristicFunc(fromNode));
            T current;

            while (openSet.Count > 0)
            {
                current = openSet.Dequeue();
                if (current.Equals(toNode))
                {
                    break;
                }

                closedSet.Add(current);
                foreach (var neighbor in neighboursFunc(current))
                {
                    if (closedSet.Contains(neighbor))
                    {
                        continue;
                    }

                    var tentativeScore = nodeScore[current] + costFunc(current, neighbor);

                    if (nodeScore.ContainsKey(neighbor) && tentativeScore >= nodeScore[neighbor])
                    {
                        continue;
                    }

                    cameFrom[neighbor]  = current;
                    nodeScore[neighbor] = tentativeScore;
                    openSet.EnqueueOrUpdate(neighbor, tentativeScore + heuristicFunc(neighbor));
                }
            }

            //Destination is unreachable
            if (!cameFrom.ContainsKey(toNode))
            {
                return(null);
            }

            var path = new List <Move <T> >();

            current = toNode;
            while (!current.Equals(fromNode))
            {
                var previous = cameFrom[current];
                path.Add(new Move <T>(previous, current, costFunc(previous, current)));
                current = previous;
            }

            path.Reverse();
            return(path);
        }
Beispiel #50
0
        static void Method(string[] args)
        {
            int[] hwk = ReadInts();
            int   h   = hwk[0];
            int   w   = hwk[1];
            int   k   = hwk[2];

            bool[,] map = new bool[h, w];
            int sX = 0, sY = 0;

            for (int i = 0; i < h; i++)
            {
                string s = Read();
                for (int j = 0; j < w; j++)
                {
                    if (s[j] == '#')
                    {
                        continue;
                    }
                    if (s[j] == 'S')
                    {
                        sX = j;
                        sY = i;
                    }
                    map[i, j] = true;
                }
            }
            long[,] distances = new long[h, w];
            for (int i = 0; i < h; i++)
            {
                for (int j = 0; j < w; j++)
                {
                    distances[i, j] = long.MaxValue / 4;
                }
            }
            int[] dx = new int[4] {
                1, -1, 0, 0
            };
            int[] dy = new int[4] {
                0, 0, 1, -1
            };
            PriorityQueue <int[]> queue = new PriorityQueue <int[]>();

            queue.Enqueue(0, new int[2] {
                sX, sY
            });
            while (queue.Count > 0)
            {
                var  pair     = queue.Dequeue();
                long distance = pair.Key;
                int  x        = pair.Value[0];
                int  y        = pair.Value[1];

                if (distance >= distances[y, x])
                {
                    continue;
                }

                distances[y, x] = distance;
                for (int i = 0; i < 4; i++)
                {
                    int nx = x + dx[i];
                    int ny = y + dy[i];
                    if (nx < 0 || w <= nx || ny < 0 || h <= ny)
                    {
                        continue;
                    }
                    long newDistance = distance + 1;
                    if (!map[ny, nx] && distance <= k)
                    {
                        newDistance = k + 1;
                    }

                    if (newDistance >= distances[ny, nx])
                    {
                        continue;
                    }
                    queue.Enqueue(newDistance, new int[2] {
                        nx, ny
                    });
                }
            }

            long res = long.MaxValue;

            for (int i = 0; i < h; i++)
            {
                for (int j = 0; j < w; j++)
                {
                    if (i == 0 || i == h - 1 || j == 0 || j == w - 1)
                    {
                        long tmp = distances[i, j] / k;
                        if (distances[i, j] % k > 0)
                        {
                            tmp++;
                        }
                        res = Min(res, tmp);
                    }
                }
            }
            WriteLine(res);
        }
Beispiel #51
0
    //Generates the initial connections from area to area. (PRIM'S ALGORITHM).
    private void generateConnections(Vertex[,] areaData)
    {
        System.Random random = new System.Random(seed); //I use the .NET Random Number Generator. No reason why.

        PriorityQueue <int, Edge> queue = new PriorityQueue <int, Edge>();

        //Add the starting point to the array.
        Vertex nextVertex = areaData[origin.x, origin.y];

        nextVertex.isConnected = true;

        queue.Enqueue(random.Next(), nextVertex.N);
        queue.Enqueue(random.Next(), nextVertex.E);
        queue.Enqueue(random.Next(), nextVertex.S);
        queue.Enqueue(random.Next(), nextVertex.W);


        /* PSEUDO-CODE
         * while the queue is not empty.
         *      Take the first value in the queue.
         *      If not already connected.
         *          Set Next Vertex to isConnected.
         *          Set BOTH edges to isUsed.
         *          Put new edges in the queue.
         */

        //while the queue is not empty.
        while (!queue.IsEmpty)
        {
            //Take the first value in the queue.
            Edge  temp      = queue.DequeueValue();
            Point tempPoint = temp.to;

            //If not already connected, and Point is a valid point on the map.
            if (withinMapBounds(tempPoint) && !areaData[tempPoint.x, tempPoint.y].isConnected)
            {
                //Set Next Vertex to isConnected.
                nextVertex             = areaData[tempPoint.x, tempPoint.y];
                nextVertex.isConnected = true;

                //Set BOTH edges to isUsed.

                //First edge.
                temp.isUsed = true;

                //Second edge.
                Point direction = temp.from - temp.to;
                if (direction.x > 0)
                {
                    nextVertex.E.isUsed = true;
                }
                else if (direction.x < 0)
                {
                    nextVertex.W.isUsed = true;
                }
                else if (direction.y > 0)
                {
                    nextVertex.N.isUsed = true;
                }
                else if (direction.y < 0)
                {
                    nextVertex.S.isUsed = true;
                }

                //Put new edges in the queue.
                if (!nextVertex.N.isUsed)
                {
                    queue.Enqueue(random.Next(), nextVertex.N);
                }
                if (!nextVertex.E.isUsed)
                {
                    queue.Enqueue(random.Next(), nextVertex.E);
                }
                if (!nextVertex.S.isUsed)
                {
                    queue.Enqueue(random.Next(), nextVertex.S);
                }
                if (!nextVertex.W.isUsed)
                {
                    queue.Enqueue(random.Next(), nextVertex.W);
                }
            }
        }
    }
Beispiel #52
0
        static void Method(string[] args)
        {
            int[] nk = ReadInts();
            int   n  = nk[0];
            int   k  = nk[1];

            int[] ps = ReadInts();

            HashSet <long>       hashSet   = new HashSet <long>();
            PriorityQueue <bool> ascQueue  = new PriorityQueue <bool>();
            PriorityQueue <bool> descQueue = new PriorityQueue <bool>();
            int incCnt = 0;

            for (int i = 0; i < k; i++)
            {
                hashSet.Add(ps[i]);
                ascQueue.Enqueue(ps[i], true);
                descQueue.Enqueue(-ps[i], true);
                if (i > 0 && ps[i] > ps[i - 1])
                {
                    incCnt++;
                }
                else
                {
                    incCnt = 0;
                }
            }
            bool ordered = incCnt == k - 1;
            int  res     = 1;

            for (int i = 1; i + k <= n; i++)
            {
                if (ps[i + k - 1] > ps[i + k - 2])
                {
                    incCnt++;
                }
                else
                {
                    incCnt = 0;
                }
                if (ascQueue.Top().Key == ps[i - 1] &&
                    -descQueue.Top().Key < ps[i + k - 1])
                {
                }
                else if (ordered && incCnt == k - 1)
                {
                }
                else
                {
                    res++;
                }
                hashSet.Remove(ps[i - 1]);
                hashSet.Add(ps[i + k - 1]);
                ascQueue.Enqueue(ps[i + k - 1], true);
                descQueue.Enqueue(-ps[i + k - 1], true);
                while (!hashSet.Contains(ascQueue.Top().Key))
                {
                    ascQueue.Dequeue();
                }
                while (!hashSet.Contains(-descQueue.Top().Key))
                {
                    descQueue.Dequeue();
                }
                if (incCnt == k - 1)
                {
                    ordered = true;
                }
            }
            WriteLine(res);
        }
Beispiel #53
0
        static void Method(string[] args)
        {
            int[] hw = ReadInts();
            int   h  = hw[0];
            int   w  = hw[1];

            int[][] abs = new int[h][];
            for (int i = 0; i < h; i++)
            {
                abs[i] = ReadInts();
                abs[i][0]--;
                abs[i][1]--;
            }

            // 始点を管理していく
            bool[] isHoles = new bool[w + 1];
            var    tree    = new LazySegmentTree2 <int, int>(
                w + 1, (a, b) => b, (a, b) => b, (a, b) => Max(a, b), 0, 0);

            for (int i = 0; i <= w; i++)
            {
                tree.Update(i, i, i);
            }
            var que = new PriorityQueue <int>();

            for (int i = 0; i < w; i++)
            {
                que.Enqueue(0, i);
            }

            for (int i = 0; i < h; i++)
            {
                int max = tree.Scan(abs[i][0], abs[i][1] + 1);
                tree.Update(abs[i][1] + 1, abs[i][1] + 1, max);
                tree.Update(abs[i][0], abs[i][1], -1);
                if (max < w && max >= 0)
                {
                    que.Enqueue(abs[i][1] + 1 - max, max);
                }

                while (que.Count > 0)
                {
                    var pair = que.Top();
                    int now  = (int)pair.Key + pair.Value;
                    if (tree.Scan(now, now) == pair.Value)
                    {
                        break;
                    }
                    que.Dequeue();
                }

                if (que.Count == 0)
                {
                    WriteLine(-1);
                }
                else
                {
                    WriteLine(que.Top().Key + i + 1);
                }
            }
        }