コード例 #1
0
        public void OnNext(long value)
        {
            // should be done with locking
            if (!_queue.Any())
            {
                CurrentTick++;
                return;
            }

            var first = _queue.GetFirst();

            while (_queue.Any() && (first.NextStateTick <= CurrentTick))
            {
                RemoveObjectFromQueue(first);
                var result = first.Act();

                if (!result)
                {
                    AddObjectToQueue(first);
                }

                if (_queue.Any())
                {
                    first = _queue.GetFirst();
                }
            }

            CurrentTick++;
        }
コード例 #2
0
        public void OnNext(long value)
        {
            // should be done with locking
            if (!_queue.Any())
            {
                CurrentTick++;
                return;
            }

            // todo maybe write use tasks here
            var first = _queue.GetFirst();

            while (_queue.Any() && (first.NextStateTick <= CurrentTick))
            {
                if (first.CurrentState == null || !first.CurrentState.Eternal)
                {
                    RemoveObjectFromQueue(first);
                    first.NextState();
                }

                /* else
                 * {
                 *   first.NextStateTick += 1;
                 * }*/

                first = _queue.GetFirst();
            }

            CurrentTick++;
        }
コード例 #3
0
        private static Dictionary <int, int> Prim(int startNode)
        {
            var tree = new Dictionary <int, int>
            {
                { startNode, 1 },
            };

            var queue = new OrderedBag <Edge>
                            (Comparer <Edge> .Create((f, s) => f.Distance - s.Distance));

            queue.AddMany(graph[startNode]);

            while (queue.Any())
            {
                var edge = queue.RemoveFirst();

                var nonTreeNode = GetNonTreeNode(tree, edge);

                if (nonTreeNode == -1)
                {
                    continue;
                }

                var treeNode = GetTreeNode(tree, edge);

                tree.Add(nonTreeNode, tree[treeNode] + 1);
                queue.AddMany(graph[nonTreeNode]);
            }

            return(tree);
        }
コード例 #4
0
ファイル: Day6.cs プロジェクト: mabargiel/AdventOfCode
        public int Part2()
        {
            var meObjectOrbit    = _map.First(x => x.Name == "YOU").OrbitsOn;
            var santaOrbitObject = _map.First(x => x.Name == "SAN").OrbitsOn;

            var vertexes = new OrderedBag <Vertex>();

            foreach (var oribitngObject in _map.Where(x => x.Name != "YOU" && x.Name != "SAN"))
            {
                vertexes.Add(new Vertex(oribitngObject, oribitngObject.Equals(meObjectOrbit) ? 0 : int.MaxValue));
            }

            while (vertexes.Any())
            {
                var u          = vertexes.RemoveFirst();
                var neighbours = vertexes.Where(x =>
                                                (x.OribitngObject.OrbitsOn.Equals(u.OribitngObject) || x.OribitngObject.Equals(u.OribitngObject.OrbitsOn)) && u.Cost + 1 < x.Cost).ToList();

                if (u.OribitngObject.Equals(santaOrbitObject))
                {
                    return(u.Cost);
                }

                foreach (var neighbour in neighbours.Where(neighbour => u.Cost + 1 < neighbour.Cost))
                {
                    neighbour.Cost = u.Cost + 1;
                }

                vertexes = new OrderedBag <Vertex>(vertexes);
            }

            return(-1);
        }
コード例 #5
0
        private static void DijsktraMostReliablePath()
        {
            reliability            = Enumerable.Repeat <double>(-1, graph.Count).ToArray();
            reliability[startNode] = 100;

            var visited = new bool[graph.Count];

            visited[startNode] = true;

            prev            = new int[graph.Count];
            prev[startNode] = -1;

            var queue = new OrderedBag <int>(
                Comparer <int> .Create((a, b) => (int)(reliability[b] - reliability[a]))); // max reliability

            queue.Add(startNode);

            while (queue.Any())
            {
                var maxNode = queue.RemoveFirst();

                if (reliability[maxNode] == -1) // no path
                {
                    break;
                }

                foreach (var edge in graph[maxNode])
                {
                    var otherNode = edge.First == maxNode
                        ? edge.Second
                        : edge.First;

                    if (!visited[otherNode])
                    {
                        visited[otherNode] = true;
                        queue.Add(otherNode);
                    }

                    // Improve realiability
                    var newReliability = reliability[maxNode] * edge.Weight / 100;
                    if (newReliability > reliability[otherNode])
                    {
                        reliability[otherNode] = newReliability;

                        prev[otherNode] = maxNode;

                        // Reorder bag
                        queue = new OrderedBag <int>(
                            queue,
                            Comparer <int> .Create((a, b) => (int)(reliability[b] - reliability[a])));
                    }
                }
            }
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: bstaykov/Telerik-DSA
 private static void PrintUnitsByAttack(int numberOfUnits)
 {
     if (!unitsByAttack.Any())
     {
         output.AppendLine(string.Format("RESULT: "));
         return;
     }
     else
     {
         var units        = unitsByAttack.Take(numberOfUnits);
         var orderedUnits = units.OrderByDescending(x => x.Attack).ThenBy(x => x.Name);
         output.AppendLine(string.Format("RESULT: {0}", string.Join(", ", orderedUnits)));
     }
 }
コード例 #7
0
        private static int FindShortestPath(int startNode)
        {
            var visited   = new bool[nodesCount];
            var distances = new int[nodesCount];

            for (int node = 0; node < nodesCount; node++)
            {
                visited[node]   = false;
                distances[node] = int.MaxValue;
            }

            OrderedBag <int> queue = new OrderedBag <int>
                                         (Comparer <int> .Create((f, s) => distances[f] - distances[s]));

            queue.Add(startNode);
            distances[startNode] = 0;

            while (queue.Any())
            {
                var node = queue.RemoveFirst();
                visited[node] = true;

                if (exit[node])
                {
                    return(distances[node]);
                }

                foreach (var edge in graph[node])
                {
                    if (!visited[edge.Node])
                    {
                        if (distances[edge.Node] > distances[node] + edge.Time)
                        {
                            distances[edge.Node] = distances[node] + edge.Time;
                        }

                        queue.Add(edge.Node);
                    }
                }
            }

            return(-1);
        }
コード例 #8
0
        private static void Prim(int startingNode)
        {
            visited.Add(startingNode);

            var priorityQueue = new OrderedBag <Edge>(
                Comparer <Edge> .Create((f, s) => f.Weight - s.Weight));

            priorityQueue.AddMany(graph[startingNode]);

            while (priorityQueue.Any())
            {
                var minEdge = priorityQueue.GetFirst();
                priorityQueue.Remove(minEdge);

                // Connect a non-tree node to the spanning tree, avoiding a cycle
                var nonTreeNode = -1;

                if (visited.Contains(minEdge.Start) &&
                    !visited.Contains(minEdge.End))
                {
                    nonTreeNode = minEdge.End;
                }

                if (!visited.Contains(minEdge.Start) &&
                    visited.Contains(minEdge.End))
                {
                    nonTreeNode = minEdge.Start;
                }

                if (nonTreeNode == -1)
                {
                    continue;
                }

                // Connect non-tree node & spanning tree
                minSpanningTree.Add(minEdge);

                visited.Add(nonTreeNode);
                priorityQueue.AddMany(graph[nonTreeNode]);
            }
        }
コード例 #9
0
ファイル: CableNetwork.cs プロジェクト: harveyntt/Algorithms
        private static void Prim()
        {
            var queue = new OrderedBag <Edge>(
                Comparer <Edge> .Create((a, b) => a.Cost - b.Cost));

            queue.AddMany(spanningTree.SelectMany(n => graph[n])); // starting nodes existing network

            while (queue.Any())
            {
                var minEdge     = queue.RemoveFirst();
                var nonTreeNode = -1;

                if (spanningTree.Contains(minEdge.First) &&
                    !spanningTree.Contains(minEdge.Second))
                {
                    nonTreeNode = minEdge.Second;
                }

                if (!spanningTree.Contains(minEdge.First) &&
                    spanningTree.Contains(minEdge.Second))
                {
                    nonTreeNode = minEdge.First;
                }

                if (nonTreeNode == -1)
                {
                    continue;
                }

                if (availableBudget < minEdge.Cost)
                {
                    break;
                }

                spanningTree.Add(nonTreeNode);
                queue.AddMany(graph[nonTreeNode]);

                availableBudget -= minEdge.Cost;
                usedBudget      += minEdge.Cost;
            }
        }
コード例 #10
0
        private static void BFS(int[] distances, int startNode, int endNode, int[] prev)
        {
            var queue = new OrderedBag <int>
                            (Comparer <int> .Create((f, s) => distances[f] - distances[s]));

            queue.Add(startNode);

            while (queue.Any())
            {
                var minNode  = queue.RemoveFirst();
                var children = edges[minNode];

                if (minNode == endNode)
                {
                    break;
                }

                foreach (var child in children)
                {
                    var childNode = child.From == minNode
                        ? child.To
                        : child.From;

                    if (distances[childNode] == int.MaxValue)
                    {
                        queue.Add(childNode);
                    }

                    var newDistances = child.Weight + distances[minNode];

                    if (newDistances < distances[childNode])
                    {
                        distances[childNode] = newDistances;
                        prev[childNode]      = minNode;

                        queue = new OrderedBag <int>
                                    (queue, Comparer <int> .Create((f, s) => distances[f] - distances[s]));
                    }
                }
            }
        }
コード例 #11
0
        private static void BFS(double[] distances, int source, int destination, int[] prev)
        {
            var queue = new OrderedBag <int>
                            (Comparer <int> .Create((f, s) => distances[s].CompareTo(distances[f])));

            queue.Add(source);

            while (queue.Any())
            {
                var node = queue.RemoveFirst();

                if (node == destination)
                {
                    break;
                }

                foreach (var edge in graph[node])
                {
                    var child = edge.First == node ? edge.Second : edge.First;

                    if (double.IsNegativeInfinity(distances[child]))
                    {
                        queue.Add(child);
                    }

                    var newDistance = distances[node] * edge.Weight / 100.0;

                    if (newDistance > distances[child])
                    {
                        distances[child] = newDistance;
                        prev[child]      = node;

                        queue = new OrderedBag <int>
                                    (queue,
                                    Comparer <int> .Create((f, s) => distances[s].CompareTo(distances[f])));
                    }
                }
            }
        }
コード例 #12
0
        private static void Prim(int node)
        {
            forest.Add(node);
            var queue = new OrderedBag <Edge>
                            (edges[node], Comparer <Edge> .Create((f, s) => f.Weight - s.Weight));

            while (queue.Any())
            {
                var edge        = queue.RemoveFirst();
                var nonTreeNode = GetNonTreeNode(edge.First, edge.Second);

                if (nonTreeNode == -1)
                {
                    continue;
                }

                Console.WriteLine($"{edge.First} - {edge.Second}");

                forest.Add(nonTreeNode);
                queue.AddMany(edges[nonTreeNode]);
            }
        }
コード例 #13
0
        private static int Prim(int budget)
        {
            var usedBudget = 0;

            var queue = new OrderedBag <Edge>
                            (Comparer <Edge> .Create((f, s) => f.Weight - s.Weight));

            foreach (var node in spaningTree)
            {
                queue.AddMany(graph[node]);
            }

            while (queue.Any())
            {
                var edge        = queue.RemoveFirst();
                var nonTreeNode = GetNonTreeNode(edge);

                if (nonTreeNode == -1)
                {
                    continue;
                }

                if (edge.Weight > budget)
                {
                    break;
                }

                usedBudget += edge.Weight;
                budget     -= edge.Weight;

                spaningTree.Add(nonTreeNode);
                queue.AddMany(graph[nonTreeNode]);
            }

            return(usedBudget);
        }
コード例 #14
0
        private static void CalcShortestPathsDijkstra()
        {
            InitializeDistances(); // infinity
            InitializePrevNodes(); // null

            var priorityQueue = new OrderedBag <Node>(
                Comparer <Node> .Create((a, b) =>
            {
                var compare = distances[a.Row][a.Col] - distances[b.Row][b.Col];     // min distance
                if (compare == 0)
                {
                    compare = a.Row - b.Row;
                }                                                  // top to bottom
                if (compare == 0)
                {
                    compare = a.Col - b.Col;
                }                                                  // left to right
                return(compare);
            }));

            priorityQueue.Add(new Node(0, 0)); // starting node

            while (priorityQueue.Any())
            {
                var minNode = priorityQueue.RemoveFirst();

                var minNodeDistance = distances[minNode.Row][minNode.Col];
                if (minNodeDistance == Infinity)
                {
                    break; // all nodes traversed
                }

                var neighbours = GetNeighbours(minNode.Row, minNode.Col);

                foreach (var neighbour in neighbours)
                {
                    // Enqueque unvisited nodes
                    var neighbourDistance = distances[neighbour.Row][neighbour.Col];
                    if (neighbourDistance == Infinity)
                    {
                        priorityQueue.Add(neighbour);
                    }

                    // Improve distance from minNode to neighbour
                    var newDistance = minNodeDistance + matrix[neighbour.Row][neighbour.Col];
                    if (newDistance < neighbourDistance)
                    {
                        distances[neighbour.Row][neighbour.Col] = newDistance;
                        prevNodes[neighbour.Row][neighbour.Col] = minNode;

                        // Reorder Queue
                        priorityQueue = new OrderedBag <Node>(priorityQueue,
                                                              Comparer <Node> .Create((a, b) =>
                        {
                            var compare = distances[a.Row][a.Col] - distances[b.Row][b.Col];
                            if (compare == 0)
                            {
                                compare = a.Row - b.Row;
                            }
                            if (compare == 0)
                            {
                                compare = a.Col - b.Col;
                            }
                            return(compare);
                        }));
                    }
                }
            }
        }
コード例 #15
0
        static void Main(string[] args)
        {
            Dictionary <string, OrderedBag <Order> >  consumerToMap = new Dictionary <string, OrderedBag <Order> >();
            OrderedDictionary <double, List <Order> > priceToMap    = new OrderedDictionary <double, List <Order> >();

            int numberOfTurns = int.Parse(Console.ReadLine());

            for (int i = 0; i < numberOfTurns; i++)
            {
                string[] commandLine = Console.ReadLine().Split(new[] { ' ' }, 2).ToArray();

                switch (commandLine[0])
                {
                case "AddOrder":
                    string[] addDetails = commandLine[1].Split(';');

                    string name     = addDetails[0];
                    double price    = double.Parse(addDetails[1]);
                    string consumer = addDetails[2];
                    Order  order    = new Order(name, consumer, price);

                    if (!priceToMap.ContainsKey(price))
                    {
                        priceToMap.Add(price, new List <Order>());
                    }
                    priceToMap[price].Add(order);

                    if (!consumerToMap.ContainsKey(consumer))
                    {
                        consumerToMap.Add(consumer, new OrderedBag <Order>());
                    }

                    consumerToMap[consumer].Add(order);

                    Console.WriteLine("Order added");
                    break;

                case "DeleteOrders":

                    if (consumerToMap.ContainsKey(commandLine[1]))
                    {
                        OrderedBag <Order> subset = consumerToMap[commandLine[1]];
                        foreach (Order set in subset)
                        {
                            priceToMap[set.Price].Remove(set);
                        }
                        consumerToMap.Remove(commandLine[1]);

                        Console.WriteLine(subset.Count + " orders deleted");
                    }
                    else
                    {
                        Console.WriteLine("No orders found");
                    }
                    break;

                case "FindOrdersByPriceRange":
                    string[] priceDetails = commandLine[1].Split(';');

                    double min = double.Parse(priceDetails[0]);
                    double max = double.Parse(priceDetails[1]);

                    OrderedBag <Order> priceBetweenMinMax = new OrderedBag <Order>();

                    foreach (var items in priceToMap.Range(min, true, max, true).Values)
                    {
                        foreach (var item in items)
                        {
                            priceBetweenMinMax.Add(item);
                        }
                    }

                    if (priceBetweenMinMax.Any())
                    {
                        foreach (Order item in priceBetweenMinMax)
                        {
                            Console.WriteLine(item);
                        }
                    }
                    else
                    {
                        Console.WriteLine("No orders found");
                    }

                    break;

                case "FindOrdersByConsumer":
                    if (consumerToMap.ContainsKey(commandLine[1]))
                    {
                        foreach (Order purchase in consumerToMap[commandLine[1]])
                        {
                            Console.WriteLine(purchase);
                        }
                    }
                    else
                    {
                        Console.WriteLine("No orders found");
                    }
                    break;
                }
            }
        }
コード例 #16
0
        static void Main()
        {
            int nodesCount = int.Parse(Console.ReadLine().Split(' ')[1]);

            string[] pathTokens = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            int      startNode  = int.Parse(pathTokens[1]);
            int      endNode    = int.Parse(pathTokens[3]);

            int edgesCount = int.Parse(Console.ReadLine().Split(' ')[1]);

            graph = new Dictionary <int, List <Edge> >();

            ReadGraph(edgesCount);

            percentages            = Enumerable.Repeat <double>(-1, graph.Count).ToArray();
            percentages[startNode] = 100;

            bool[] visited = new bool[graph.Count];
            visited[startNode] = true;

            previous            = new int[graph.Count];
            previous[startNode] = -1;

            //Djikstra's algorithm

            var queue = new OrderedBag <int>(Comparer <int> .Create((a, b) => (int)(percentages[b] - percentages[a])));

            queue.Add(startNode);

            while (queue.Any())
            {
                int nodeWithMaxPercentage = queue.RemoveFirst();

                if (percentages[nodeWithMaxPercentage] == -1)
                {
                    break; //reached a node with no path further
                }

                foreach (Edge edge in graph[nodeWithMaxPercentage])
                {
                    var otherNode = edge.FirstNode == nodeWithMaxPercentage
                        ? edge.SecondNode
                        : edge.FirstNode;

                    if (!visited[otherNode])
                    {
                        visited[otherNode] = true;
                        queue.Add(otherNode);
                    }

                    double newPercentage = percentages[nodeWithMaxPercentage] / 100 * edge.Cost;

                    if (percentages[otherNode] < newPercentage)
                    {
                        percentages[otherNode] = newPercentage;
                        previous[otherNode]    = nodeWithMaxPercentage;

                        //have yo sort again because percentages has changed
                        queue = new OrderedBag <int>(
                            queue,
                            Comparer <int> .Create((a, b) => (int)(percentages[b] - percentages[a])));
                    }
                }
            }

            PrintMostReliablePath(endNode);
        }
コード例 #17
0
        static void Main(string[] args)
        {
            var nodesCount = int.Parse(Console.ReadLine());
            var edgesCount = int.Parse(Console.ReadLine());
            var startNode  = int.Parse(Console.ReadLine());

            graph = ReadGraph(nodesCount, edgesCount);

            var distances = new double[nodesCount];

            for (int node = 0; node < distances.Length; node++)
            {
                distances[node] = double.PositiveInfinity;
            }

            var queue = new OrderedBag <int>
                            (Comparer <int> .Create((f, s) => distances[f].CompareTo(distances[s])));

            foreach (var edge in graph[startNode])
            {
                distances[edge.To] = edge.Distance;
                queue.Add(edge.To);
            }

            var visited = new HashSet <int> {
                startNode
            };

            while (queue.Any())
            {
                var node = queue.RemoveFirst();
                visited.Add(node);

                if (node == startNode)
                {
                    break;
                }

                foreach (var edge in graph[node])
                {
                    var child = edge.To;

                    if (double.IsPositiveInfinity(distances[child]))
                    {
                        queue.Add(child);
                    }

                    var newDistance = distances[node] + edge.Distance;
                    if (newDistance < distances[child])
                    {
                        distances[child] = newDistance;

                        queue = new OrderedBag <int>
                                    (queue, Comparer <int> .Create((f, s) => distances[f].CompareTo(distances[s])));
                    }
                }
            }

            if (double.IsPositiveInfinity(distances[startNode]))
            {
                Console.WriteLine(visited.Count);
            }
            else
            {
                Console.WriteLine(distances[startNode]);
            }
        }