Пример #1
0
        public void TestMethodNext()
        {
            var client1 = new Client
            {
                Num      = 100,
                Data     = DateTime.Now,
                Priority = 5
            };

            var client2 = new Client
            {
                Num      = 2,
                Data     = DateTime.Now,
                Priority = 5
            };

            var client3 = new Client
            {
                Num      = 3,
                Data     = DateTime.Now,
                Priority = 5
            };



            var fila = new Queue <Client>();

            var myQueue = new PQueue(fila);

            myQueue.Add(client1);
            myQueue.Add(client3);
            myQueue.Add(client2);

            Assert.AreEqual(100, myQueue.Next());
        }
Пример #2
0
        public Puzzle(int[,] initialBoard)
        {
            State startingState = createStartingState(initialBoard);

            PendingStates = new PQueue();
            PendingStates.Push(startingState);
            StatesExplored = 0;
        }
Пример #3
0
        public void Count_should_become_greater_after_Enqueue()
        {
            int expectCount = 1;

            queue = new PQueue <TileNode>();

            queue.Enqueue(fixture.Create <TileNode>(), 0);
            int actualeCount = queue.Count;

            Assert.AreEqual(expectCount, actualeCount);
        }
Пример #4
0
        public void CanIdentifyRegexLexem()
        {
            var input = "banan";
            var expected = new PQueue<Token>();
            expected.Enqueue(new Token { TokenType = TokenType.NAME, Value = "banan" });

            var actual = sut.Tokenize(input);
            Assert.AreEqual(expected.First().TokenType, actual.First().TokenType);
            Assert.AreEqual(expected.First().Value, actual.First().Value);
            Assert.AreEqual(expected.Count, actual.Count);
        }
Пример #5
0
 void Awake()
 {
     Random.seed = 1;
     Noise.init();
     _needsGenerated   = new PQueue <ChunkInfo>();
     _needsMesh        = new PQueue <ChunkInfo>();
     _running          = true;
     generationThread1 = new System.Threading.Thread(generateChunks);
     generationThread1.Start();
     _isGenerating = true;
 }
Пример #6
0
        public PQueue<Token> Tokenize(string input)
        {
            var queue = new PQueue<Token>();

            foreach (var token in LexerOutput)
            {
                queue.Enqueue(token);
            }

            return queue;
        }
Пример #7
0
        public void CanCreateSingleLexem()
        {
            var input = "if";
            var expected = new PQueue<Token>();
            expected.Enqueue(new Token { TokenType = TokenType.IF, Value = "if" });

            var actual = sut.Tokenize(input);
            Assert.AreEqual(expected.First().TokenType, actual.First().TokenType);
            Assert.AreEqual(expected.First().Value, actual.First().Value);
            Assert.AreEqual(expected.Count, actual.Count);
        }
Пример #8
0
        public void Count_should_become_less_after_Dequeue()
        {
            int expectedCount = 0;

            queue = new PQueue <TileNode>();

            queue.Enqueue(fixture.Create <TileNode>(), 1);
            queue.Dequeue();
            int actualeCount = queue.Count;

            Assert.AreEqual(expectedCount, actualeCount);
        }
Пример #9
0
        public PQueue<Token> Tokenize(string input)
        {
            var output = new PQueue<Token>();
            index = 0;
            this.input = input;
            Token nextToken;

            while ((nextToken = FetchNextToken()) != null)
                if (nextToken.TokenType != TokenType.WHITESPACE)
                    output.Enqueue(nextToken);

            return output;
        }
Пример #10
0
        public void Dequeue_should_return_first_come_object_if_all_objects_has_same_priority()
        {
            TileNode expectedTile = fixture.Create <TileNode>();

            queue = new PQueue <TileNode>();

            queue.Enqueue(expectedTile, 0);
            queue.Enqueue(fixture.Create <TileNode>(), 0);
            queue.Enqueue(fixture.Create <TileNode>(), 0);
            TileNode actualeTile = queue.Dequeue();

            Assert.AreEqual(expectedTile, actualeTile);
        }
Пример #11
0
        public void Dequeue_should_return_first_object_with_lowest_priority()
        {
            TileNode expectedTile = fixture.Create <TileNode>();

            queue = new PQueue <TileNode>();

            queue.Enqueue(fixture.Create <TileNode>(), 1);
            queue.Enqueue(expectedTile, 0);
            queue.Enqueue(fixture.Create <TileNode>(), 0);
            TileNode actualeTile = queue.Dequeue();

            Assert.AreEqual(expectedTile, actualeTile);
        }
Пример #12
0
        protected void DoWork()
        {
            try
            {
                Int32 delay = 0;
#if !DEBUG
                if (this.SyncOnHour)
                {
                    DateTime now  = DateTime.Now;
                    DateTime last = new DateTime(now.Year, now.Month, now.Day, now.Hour, 0, 0);
                    delay = (60 * 60 * 1000) - ((Int32)((DateTime.Now - last).TotalMilliseconds));
                    if (delay < 0)
                    {
                        delay = 0;
                    }
                }
                delay += this.Stagger;
#endif
                Logger.Log(EnLogLevel.INFO, string.Format("Processor starting delay: {0}.", delay));

                if (delay > 0)
                {
                    System.Threading.Thread.Sleep((Int32)delay);
                }
                this.Producer(DateTime.Now);

                this.m_BaseTimer          = new System.Timers.Timer();
                this.m_BaseTimer.Interval = this.Interval;
                this.m_BaseTimer.Elapsed += new System.Timers.ElapsedEventHandler(m_BaseTimer_Elapsed);
                this.m_BaseTimer.Enabled  = true;

                while (Processing)
                {
                    try
                    {
                        object o = PQueue.Consume();
                        Consumer(o);
                    }
                    catch (Exception e)
                    {
                        Logger.LogException(e);
                    }
                }
                Logger.Log(EnLogLevel.INFO, "ProcessQueueThread() - Thread procedure stopping.");
            }
            catch (Exception e)
            {
                Logger.LogException(e);
            }
        }
Пример #13
0
        public void IgnoresWhiteSpaceInExpressions()
        {
            var input = "if (";
            var expected = new PQueue<Token>();
            expected.Enqueue(new Token { TokenType = TokenType.IF, Value = "if" });
            expected.Enqueue(new Token { TokenType = TokenType.LPAR, Value = "(" });

            var actual = sut.Tokenize(input);

            Assert.AreEqual(expected.Count, actual.Count);
            Assert.AreEqual(expected.First().TokenType, actual.First().TokenType);
            Assert.AreEqual(expected.First().Value, actual.First().Value);
            Assert.AreEqual(expected.Last().TokenType, actual.Last().TokenType);
            Assert.AreEqual(expected.Last().Value, actual.Last().Value);
        }
Пример #14
0
        public void CanCreateSingleLexem()
        {
            var input    = "if";
            var expected = new PQueue <Token>();

            expected.Enqueue(new Token {
                TokenType = TokenType.IF, Value = "if"
            });

            var actual = sut.Tokenize(input);

            Assert.AreEqual(expected.First().TokenType, actual.First().TokenType);
            Assert.AreEqual(expected.First().Value, actual.First().Value);
            Assert.AreEqual(expected.Count, actual.Count);
        }
Пример #15
0
        public void CanIdentifyRegexLexem()
        {
            var input    = "banan";
            var expected = new PQueue <Token>();

            expected.Enqueue(new Token {
                TokenType = TokenType.NAME, Value = "banan"
            });

            var actual = sut.Tokenize(input);

            Assert.AreEqual(expected.First().TokenType, actual.First().TokenType);
            Assert.AreEqual(expected.First().Value, actual.First().Value);
            Assert.AreEqual(expected.Count, actual.Count);
        }
Пример #16
0
        public static ModellingLog Run(model m, double tmax = 100)
        {
            double currtime = 0;
            PQueue q        = new PQueue();

            //fill pqueue
            while (currtime < tmax && q.Count > 0)
            {
                var e = q.Dequeue();
                //process event
            }



            return(null);
        }
Пример #17
0
        public void IgnoresWhiteSpaceInExpressions()
        {
            var input    = "if (";
            var expected = new PQueue <Token>();

            expected.Enqueue(new Token {
                TokenType = TokenType.IF, Value = "if"
            });
            expected.Enqueue(new Token {
                TokenType = TokenType.LPAR, Value = "("
            });

            var actual = sut.Tokenize(input);

            Assert.AreEqual(expected.Count, actual.Count);
            Assert.AreEqual(expected.First().TokenType, actual.First().TokenType);
            Assert.AreEqual(expected.First().Value, actual.First().Value);
            Assert.AreEqual(expected.Last().TokenType, actual.Last().TokenType);
            Assert.AreEqual(expected.Last().Value, actual.Last().Value);
        }
Пример #18
0
    static void Main()
    {
        PQueue erwait = new PQueue();

        pqItem[] erPatient = new pqItem[4];
        pqItem   nextPatient;

        erPatient[0].name     = "Joe Smith";
        erPatient[0].priority = 1;
        erPatient[1].name     = "Mary Brown";
        erPatient[1].priority = 0;
        erPatient[2].name     = "Sam Jones";
        erPatient[2].priority = 3;
        for (int x = 0; x <= erPatient.GetUpperBound(0); x++)
        {
            erwait.Enqueue(erPatient[x]);
        }
        nextPatient = (pqItem)erwait.Dequeue();
        Console.WriteLine(nextPatient.name);
    }
Пример #19
0
        public PQueue<Token> Tokenize(string input)
        {
            output = new PQueue<Token>();

            TempPreprocess(ref input);

            index = 0;
            this.input = input;
            Token nextToken;

            while ((nextToken = FetchNextToken()) != null)
            {
                if (nextToken.TokenType != TokenType.WHITESPACE)
                    output.Enqueue(nextToken);

                // If this is a new line, calculate the indentation level:
                if (nextToken.TokenType == TokenType.NEWLINE)
                    GenerateIndentDedentTokens();
            }

            return output;
        }
Пример #20
0
        public static void ConstructHuffmanTree(ref HuffmanNode root, PQueue <HuffmanNode> q)
        {
            while (q.Size() > 1)
            {
                HuffmanNode x = q.Peek();
                q.Pop();

                HuffmanNode y = q.Peek();
                q.Pop();

                HuffmanNode f = new HuffmanNode();

                f.Data      = x.Data + y.Data;
                f.Character = '-';

                f.Left  = x;
                f.Right = y;

                root = f;

                q.Add(f);
            }
        }
Пример #21
0
 public void Setup()
 {
     lexerStub = MockRepository.GenerateStub<ILexer>();
     sut = new SimpleParser(lexerStub);
     mockTokens = new PQueue<Token>();
 }
Пример #22
0
        /// <summary>
        /// The main method to call when parsing
        /// </summary>
        /// <param name="input"></param>
        public void Parse(string input)
        {
            m_err.Clear();
            m_consumed.Clear();

            try
            {
                m_sym = m_lexer.Tokenize(input);
            }
            catch (LexerException ex)
            {
                throw new ParserException("Parsing failed", ex);
            }

            // Stmt == Terminating rule
            //Stmt();
            Prg();

            // If we still have symbols in the stream, parsing failed
            if (m_sym.Count > 0)
                m_err.Enqueue(new Error { Message = "Syntax Error - Unmatched tokens", Type = ErrorType.SyntaxError });

            // If parsing failed, reset the tree
            if (m_err.Count > 0)
                m_tree = null;
        }
Пример #23
0
    public List<Waypoint> ShortestPath(Waypoint a, Waypoint b)
    {
        Dictionary<Waypoint, Waypoint> cameFrom = new Dictionary<Waypoint, Waypoint> ();
        Dictionary<Waypoint, float> costSoFar = new Dictionary<Waypoint, float> ();
        PQueue frontier = new PQueue();
        cameFrom[a] = null;
        costSoFar [a] = 0f;
        frontier.push (a, 0);
        while (!frontier.empty ()) {
            Waypoint current = frontier.pop ();
            if (current == b)
                break;
            foreach (Waypoint next in current.connections) {
                float newCost = costSoFar [current] + Waypoint.distance (current, next);
                if (!costSoFar.ContainsKey(next) || newCost < costSoFar[next]) {
                    costSoFar [next] = newCost;
                    frontier.push (next, newCost);
                    cameFrom [next] = current;
                }
            }
        }

        List<Waypoint> path = new List<Waypoint> ();
        Waypoint point = b;
        while (point != a) {
            path.Add (point);
            point = cameFrom[point];
        }
        path.Add (a);
        path.Reverse ();
        return path;
    }
Пример #24
0
 virtual protected void Producer(DateTime timestamp)
 {
     PQueue.Produce(timestamp);
 }
Пример #25
0
    public void SearchForPath()
    {
        PQueue <Vector3Int> queue = new PQueue <Vector3Int>();

        queue.AddToQueue(mStartPos, 0f);

        positionsVisited.Add(mStartPos, mStartPos);
        collectiveCost.Add(mStartPos, 0f);

        while (queue.Count > 0f)
        {
            Vector3Int currentPoint = queue.PopFromQueue();

            if (currentPoint == mDestPos)
            {
                break;
            }

            for (int x = -1; x <= 1; x++)
            {
                for (int y = -1; y <= 1; y++)
                {
                    for (int z = -1; z <= 1; z++)
                    {
                        if ((x != 0 && z != 0) || (x != 0 && y != 0) || (z != 0 && y != 0))
                        {
                            continue;
                        }
                        if ((currentPoint.x + x) < 0 ||
                            (currentPoint.y + y) < 0 ||
                            (currentPoint.z + z) < 0 ||
                            (currentPoint.x + x) > Map.Instance.mapSize.x - 1 ||
                            (currentPoint.y + y) > Map.Instance.mapSize.y - 1 ||
                            (currentPoint.z + z) > Map.Instance.mapSize.z - 1 ||
                            (x == 0 && y == 0 && z == 0))
                        {
                            continue;
                        }

                        if (Map.Instance.mapAry[currentPoint.x + x, currentPoint.y + y, currentPoint.z + z].type == NodeType.Wall)
                        {
                            continue;
                        }

                        Vector3Int neighbourPoint = new Vector3Int(currentPoint.x + x, currentPoint.y + y, currentPoint.z + z);
                        float      newCost        = collectiveCost[currentPoint] + (currentPoint - neighbourPoint).magnitude;

                        if (!collectiveCost.ContainsKey(neighbourPoint) || newCost < collectiveCost[neighbourPoint])
                        {
                            if (collectiveCost.ContainsKey(neighbourPoint))
                            {
                                collectiveCost.Remove(neighbourPoint);
                                positionsVisited.Remove(neighbourPoint);
                            }

                            collectiveCost.Add(neighbourPoint, newCost);
                            positionsVisited.Add(neighbourPoint, currentPoint);

                            float priorityValue = newCost + GetHeuristic(neighbourPoint, mDestPos);
                            queue.AddToQueue(neighbourPoint, priorityValue);
                        }
                    }
                }
            }
        }
    }
Пример #26
0
        /// <summary>
        /// performs a Branch and Bound search of the state space of partial tours
        /// stops when time limit expires and uses BSSF as solution
        /// </summary>
        /// <returns>results array for GUI that contains three ints: cost of solution, time spent to find solution, number of solutions found during search (not counting initial BSSF estimate)</returns>
        public string[] bBSolveProblem()
        {
            string[]  results = new string[3];
            Stopwatch timer   = new Stopwatch();

            //set initial bssff
            initialBssf = true;
            greedySolveProblem();
            int       validRoutes             = 0;
            int       prunes                  = 0;
            int       states                  = 0;
            int       updates                 = 0;
            int       maxNumberOfStatesStored = 0;
            ArrayList routeResult             = new ArrayList();
            State     currentNode             = new State(new RMatrix(Cities), Cities[0], 0, Cities.Length);
            PQueue    queue = new PQueue(Cities.Length);

            states++;
            if (currentNode.bssfCost < bssf.costOfRoute())
            {
                queue.add(currentNode);
            }
            timer.Start();
            Console.WriteLine("Started bb timer");
            while (!queue.empty())
            {
                long time = timer.ElapsedMilliseconds;
                if (time > time_limit)
                {
                    Console.WriteLine("Timed out");
                    break;
                }
                //get next node
                currentNode = queue.deleteMin();
                if (currentNode.bssfCost >= bssf.costOfRoute())
                {
                    prunes++;
                    queue.pruneCurrentPath();
                    continue;
                }
                //check if we have completed route
                if (currentNode.route.Count == Cities.Length)
                {
                    double cost = currentNode.city.costToGetTo(Cities[0]);
                    //check if we can get back to the starting city
                    if (!double.IsPositiveInfinity(cost))
                    {
                        validRoutes++;
                        //check if route is better that bssf
                        if (currentNode.currentCost + cost < bssf.costOfRoute())
                        {
                            currentNode.currentCost += cost;
                            updates++;
                            bssf = new TSPSolution(currentNode.route);
                        }
                    }
                }
                //expand node
                for (int i = 0; i < Cities.Length; i++)
                {
                    if (currentNode.visited.Contains(i))
                    {
                        continue;
                    }
                    double costToCity = currentNode.city.costToGetTo(Cities[i]);
                    // if we can reach the city
                    if (!double.IsPositiveInfinity(costToCity))
                    {
                        //create a new state for the next possible city
                        State node = new State(currentNode, costToCity, i, Cities[i], Cities.Length);
                        states++;
                        //if the lower bound for the new state is lower than the bssf, add to queue
                        if (node.bssfCost < bssf.costOfRoute())
                        {
                            queue.add(node);
                            //update maxNumberOfStatesStored counter
                            if (queue.count > maxNumberOfStatesStored)
                            {
                                maxNumberOfStatesStored = queue.count;
                            }
                        }
                        else
                        {
                            prunes++;
                        }
                    }
                }
            }
            timer.Stop();
            Console.WriteLine("Stopped bb timer");
            Console.WriteLine("-------------------");
            Console.WriteLine("Results:");
            Console.WriteLine("Number of solutions: " + validRoutes);
            Console.WriteLine("Max number of states: " + maxNumberOfStatesStored);
            Console.WriteLine("Number of updates:" + updates);
            Console.WriteLine("Number of states:" + states);
            Console.WriteLine("Number of prunes: " + prunes);
            Console.WriteLine("-------------------");

            results[COST] = bssf.costOfRoute().ToString();
            double elapsedTime = timer.Elapsed.TotalSeconds;;

            results[TIME]  = elapsedTime.ToString();
            results[COUNT] = validRoutes.ToString();

            return(results);
        }
Пример #27
0
        public static RouteInfo FindRoute(int start, int end)
        {
            //list of visited vertexes
            ArrayList closed = new ArrayList();

            //priority queue of not visited vertexes
            PQueue open = new PQueue();

            //resulted route
            RouteInfo route = new RouteInfo();

            route.Towns = new System.Collections.Generic.List <int>();
            route.Towns.Add(start);


            //put all start vertex neighbours to the open collection
            //put the start to the closed
            closed.Add(start);

            for (int i = 0; i < RoutesManager.Length; i++)
            {
                if (RoutesManager.AdjacencyMatrix[start, i] != 0)
                {
                    VertexInfo toPush = new VertexInfo();
                    toPush.Distance = RoutesManager.AdjacencyMatrix[start, i];
                    toPush.Priority = RoutesManager.EvristicMatrix[i, end] + toPush.Distance;
                    toPush.Town     = i;

                    //push to the queue
                    open.Push(toPush);
                }
            }


            while (open.Capacity > 0)
            {
                //get the lowest evristic value
                var current = open.Pop();

                //the route has already found
                if (current.Town == end)
                {
                    //add the last node
                    route.Towns.Add(current.Town);
                    break;
                }

                //add town to the closed list
                closed.Add(current.Town);

                //new vertex to add to the open list
                VertexInfo toPush = new VertexInfo();



                //discovet the neighbours
                //that is not in closed list
                for (int i = 0; i < RoutesManager.Length; i++)
                {
                    if (RoutesManager.AdjacencyMatrix[current.Town, i] != 0 && !closed.Contains(i))
                    {
                        int tentative = RoutesManager.AdjacencyMatrix[current.Town, i] + current.Distance;

                        if (tentative > RoutesManager.AdjacencyMatrix[start, i])
                        {
                            //add distances to the current node and from current to i
                            toPush.Distance += RoutesManager.AdjacencyMatrix[current.Town, i];
                            toPush.Distance += current.Distance;


                            toPush.Priority = RoutesManager.EvristicMatrix[i, end];
                            toPush.Town     = i;


                            //push to the queue
                            open.Push(toPush);
                        }
                    }
                }


                route.Towns.Add(current.Town);
            }



            //calculate length
            for (int i = 0; i < route.Towns.Count - 1; i++)
            {
                route.Length += RoutesManager.AdjacencyMatrix[route.Towns[i], route.Towns[i + 1]];
            }

            return(route);
        }
Пример #28
0
 public void Setup()
 {
     sut = new PQueue <int>();
 }
Пример #29
0
 public void Setup()
 {
     lexerStub  = MockRepository.GenerateStub <ILexer>();
     sut        = new SimpleParser(lexerStub);
     mockTokens = new PQueue <Token>();
 }
Пример #30
0
 public void Setup()
 {
     sut = new PQueue<int>();
 }
Пример #31
0
    public bool FindPath(ANode root, ANode dest)
    {
        PQueue queue = new PQueue();

        if (!nodes.Contains(root))
        {
            nodes.Add(root);
            foreach (APath x in root.GetPaths())
            {
                paths.Add(x);
            }
        }

        if (!nodes.Contains(dest))
        {
            nodes.Add(dest);
            foreach (APath x in dest.GetPaths())
            {
                paths.Add(x);
            }
        }

        ANode currentNode = root;

        currentNode.Cost = 0;

        List <ANode> notVisited = new List <ANode>(nodes);

        while (notVisited.Count > 0)
        {
            foreach (APath x in currentNode.GetPaths())
            {
                ANode neighbor = x.GetOtherSide(currentNode);
                if (neighbor.Visited)
                {
                    continue;
                }

                neighbor.UpdateHeuristic(GetHeuristicOf(neighbor, dest));

                if (neighbor.Cost > currentNode.Cost + x.Cost)
                {
                    neighbor.UpdateNodeCost(currentNode.Cost + x.Cost, currentNode);
                }

                queue.Enqueue(neighbor);
            }
            currentNode.Visited = true;
            notVisited.Remove(currentNode);
            if (notVisited.Count == 0)
            {
                break;
            }
            currentNode = queue.Dequeue();
            if (currentNode.Equals(dest))
            {
                UpdatePath(root, dest);
                return(true);
            }
        }

        return(false);
    }