public AStarSearch(WeightedGraph<Position> graph, Position start, Position goal)
    {
        var frontier = new SimplePriorityQueue<Position>();
        frontier.Enqueue(start, 0);

        cameFrom[start] = start;
        costSoFar[start] = 0;

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

            if(current.Equals(goal))
            {
                break;
            }

            foreach (var next in graph.Neighbors(current))
            {
                int newCost = costSoFar[current] + graph.Cost(current, next);
                if (!costSoFar.ContainsKey(next) || newCost < costSoFar[next])
                {
                    costSoFar[next] = newCost;
                    int priority = newCost + Heuristic(next, goal);
                    frontier.Enqueue(next, priority);
                    cameFrom[next] = current;
                }
            }
        } 
    }
Exemplo n.º 2
0
        public void testWeightedAddEdge()
        {
            WeightedGraph<int> graph = new WeightedGraph<int>();
            int num1 = 1;
            int num2 = 2;
            int num3 = 3;
            int num4 = 4;
            int num5 = 5;

            graph.addEdge(num1, num2);
            graph.addEdge(num2, num3);
            graph.addEdge(num3, num4);
            graph.addEdge(num4, num5);
            graph.addEdge(num1, num3);

            Assert.IsTrue(graph.numVertices == 5);
            Assert.IsTrue(graph.AdjacencyList.ContainsKey(num1));
            Assert.IsTrue(graph.AdjacencyList.ContainsKey(num2));
            Assert.IsTrue(graph.AdjacencyList.ContainsKey(num3));
            Assert.IsTrue(graph.AdjacencyList.ContainsKey(num4));
            Assert.IsTrue(graph.AdjacencyList.ContainsKey(num5));

            Assert.IsNotNull(graph.AdjacencyList[num1]);
            Assert.IsNotNull(graph.AdjacencyList[num2]);
            Assert.IsNotNull(graph.AdjacencyList[num3]);
            Assert.IsNotNull(graph.AdjacencyList[num4]);
            Assert.IsNotNull(graph.AdjacencyList[num5]);

            Assert.IsTrue(graph.AdjacencyList[num1].Count == 2);
            Assert.IsTrue(graph.AdjacencyList[num2].Count == 2);
            Assert.IsTrue(graph.AdjacencyList[num3].Count == 3);
            Assert.IsTrue(graph.AdjacencyList[num4].Count == 2);
            Assert.IsTrue(graph.AdjacencyList[num5].Count == 1);
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            int houses = 10;
            WeightedGraph<int> graph = new WeightedGraph<int>(houses);
            for (int i = 0; i < houses; i++)
            {
                graph.Add(i);
            }

            //edges are undirected
            graph.AttachEdge(0, 2, 7);
            graph.AttachEdge(0, 7, 10);
            graph.AttachEdge(1, 2, 2);
            graph.AttachEdge(1, 5, 5);
            graph.AttachEdge(3, 6, 6);
            graph.AttachEdge(3, 9, 5);
            graph.AttachEdge(4, 8, 5);
            graph.AttachEdge(5, 6, 1);
            graph.AttachEdge(7, 8, 2);
            graph.AttachEdge(8, 9, 2);

            string result = graph.MinimalSpanningTree();
            Console.WriteLine(result);
            
        }
    /// <summary>
    /// Konstruktor für minimalen Spannbaum
    /// </summary>
    /// <param name="g">GeoGraph aus dem ein 
    /// minimaler Spannbaum erstellt werden soll</param>
    public MinimumSpanningTree(GeoGraph g)
    {
        this.sourceGraph = g;
        this.form = new Form();
        this.form.Show();

        computeMinimumSpanningTree();
    }
Exemplo n.º 5
0
        public override IEnumerable <object> Solve(TextReader inputStream)
        {
            var(nodeCount, edgeCount, penalty) = inputStream.ReadValue <int, int, int>();
            var graph = new WeightedGraph(nodeCount);

            for (int i = 0; i < edgeCount; i++)
            {
                var(from, to, coin) = inputStream.ReadValue <int, int, int>();
                from--;
                to--;
                graph.AddEdge(new WeightedEdge(from, to, penalty - coin));
            }

            var bf = new BellmanFord <BasicNode, WeightedEdge>(graph);

            var(distances, negativeCycles) = bf.GetDistancesFrom(new BasicNode(0));

            if (negativeCycles[^ 1])
Exemplo n.º 6
0
        public void _Sequence_ReadWrite()
        {
            var graph  = new WeightedGraph <object, int>(false, Round);
            var random = new Random(DateTime.Now.Millisecond);

            for (int i = 0; i < Round; i++)
            {
                graph.Set(i, i);
            }
            for (int i = 0; i < Round * 4.5; i++)
            {
                graph.AddEdge(random.Next(0, Round - 1), random.Next(0, Round - 1));
            }
            for (int i = 0; i < Round; i++)
            {
                Assert.True(i == (int)graph[i].Value);
            }
        }
        public void WeightedGraph_Smoke_Test()
        {
            var graph = new WeightedGraph <int, int>();

            graph.AddVertex(1);
            graph.AddVertex(2);
            graph.AddVertex(3);
            graph.AddVertex(4);
            graph.AddVertex(5);

            graph.AddEdge(1, 2, 1);
            graph.AddEdge(2, 3, 2);
            graph.AddEdge(3, 4, 4);
            graph.AddEdge(4, 5, 5);
            graph.AddEdge(4, 1, 1);
            graph.AddEdge(3, 5, 6);

            Assert.AreEqual(2, graph.GetAllEdges(2).Count);

            Assert.AreEqual(5, graph.VerticesCount);

            Assert.IsTrue(graph.HasEdge(1, 2));

            graph.RemoveEdge(1, 2);

            Assert.IsFalse(graph.HasEdge(1, 2));

            graph.RemoveEdge(2, 3);
            graph.RemoveEdge(3, 4);
            graph.RemoveEdge(4, 5);
            graph.RemoveEdge(4, 1);

            Assert.IsTrue(graph.HasEdge(3, 5));
            graph.RemoveEdge(3, 5);
            Assert.IsFalse(graph.HasEdge(3, 5));

            graph.RemoveVertex(1);
            graph.RemoveVertex(2);
            graph.RemoveVertex(3);
            graph.RemoveVertex(4);
            graph.RemoveVertex(5);

            Assert.AreEqual(0, graph.VerticesCount);
        }
        public void TestExpandingEdges()
        {
            var graph = new WeightedGraph <Char>((oldEdge, newEdge) => newEdge > oldEdge);

            var a = new CharWeightedNode('A');
            var b = new CharWeightedNode('B');

            graph.AddNode(a);
            graph.AddNode(b);

            graph.AddUndirectedEdge(a, b, 10);
            Assert.AreEqual(10, a.Cost(b));

            graph.UpdateUndirectedEdge(a, b, 20);
            Assert.AreEqual(20, a.Cost(b));

            graph.UpdateUndirectedEdge(a, b, 6);
            Assert.AreEqual(20, a.Cost(b));
        }
Exemplo n.º 9
0
        private void DrawPath(int start, int end, InfoTextLabel infoText)
        {
            WeightedGraph weightedGraph = new WeightedGraph(adList);

            path = weightedGraph.FindShortestPath(start, end);

            if (SumWeightPath(path) == 0)
            {
                infoText.Text = "Path: is not exist";
            }
            else
            {
                infoText.Text += Convert.ToString(SumWeightPath(path));
            }

            ChangeColorEdges(BrushColor.Yellow);

            drawForm.Refresh();
        }
        public void TraverseTest()
        {
            var graph = new WeightedGraph <string, int>();

            var one = new WeightedGraph <string, int> .WeightedNode("one");

            var two = new WeightedGraph <string, int> .WeightedNode("two");

            var three = new WeightedGraph <string, int> .WeightedNode("three");

            var four = new WeightedGraph <string, int> .WeightedNode("four");

            var five = new WeightedGraph <string, int> .WeightedNode("five");

            graph.Nodes.Add(one);
            graph.Nodes.Add(two);
            graph.Nodes.Add(three);
            graph.Nodes.Add(four);
            graph.Nodes.Add(five);

            graph.Connect(one, two, 5);
            graph.Connect(one, five, 2);
            graph.Connect(two, five, 1);
            graph.Connect(two, four, 8);
            graph.Connect(two, three, 1);
            graph.Connect(four, five, 15);
            graph.Connect(four, three, 13);

            graph.StartNode = one;

            var visitedOrder = new List <string>();

            foreach (var node in graph)
            {
                visitedOrder.Add(node);
            }

            Assert.AreEqual("one", visitedOrder[0]);
            Assert.AreEqual("five", visitedOrder[1]);
            Assert.AreEqual("two", visitedOrder[2]);
            Assert.AreEqual("three", visitedOrder[3]);
            Assert.AreEqual("four", visitedOrder[4]);
        }
Exemplo n.º 11
0
        public void ABC137Test_FromEdges(string testCaseName)
        {
            ABC137Test_Core(testCaseName, (nodesCount, edgesCount, penalty, io) =>
            {
                var graph       = new WeightedGraph(nodesCount);
                var bellmanFord = new BellmanFord(nodesCount);

                for (int i = 0; i < edgesCount; i++)
                {
                    var abc = io.ReadIntArray(3);
                    var a   = abc[0] - 1;
                    var b   = abc[1] - 1;
                    var c   = abc[2];
                    bellmanFord.AddEdge(a, b, penalty - c);
                }

                return(bellmanFord);
            });
        }
Exemplo n.º 12
0
 private void Visit(WeightedGraph G, int v)
 {
     marked[v] = true;
     foreach (var e in G.adj(v))
     {
         int w = e.other(v);
         if (!marked[w])
         {
             if (!pq.Contains(w))
             {
                 pq.Insert(w, e);
             }
             else
             {
                 pq.DecreaseKey(w, e);
             }
         }
     }
 }
Exemplo n.º 13
0
        public AStarSearch(WeightedGraph <Vector3Int> graph, Vector3Int start, Vector3Int destination)
        {
            var frontier = new PriorityQueue <Vector3Int>();

            frontier.Enqueue(start, 0);

            CameFrom[start]  = start;
            CostSoFar[start] = 0;

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

                if (current.Equals(destination))
                {
                    Path.Add(current);
                    var rear = current;

                    while (CameFrom.ContainsKey(rear) && CameFrom[rear] != rear)
                    {
                        Path.Add(CameFrom[rear]);
                        rear = CameFrom[rear];
                    }

                    Path.Reverse();
                    break;
                }

                foreach (var next in graph.Neighbors(current))
                {
                    var newCost = CostSoFar[current] + graph.Cost(current, next);

                    if (!CostSoFar.ContainsKey(next) || newCost < CostSoFar[next])
                    {
                        CostSoFar[next] = newCost;
                        var priority = newCost + Heuristic(next, destination);
                        frontier.Enqueue(next, priority);
                        CameFrom[next] = current;
                    }
                }
            }
        }
Exemplo n.º 14
0
        public static PathResolver <Node> Solver(WeightedGraph <Node> graph, Node source, Node destination, SearchTypes search)
        {
            switch (search)
            {
            case SearchTypes.DFS:
                return(new DFS <Node>(graph, source, destination));

            case SearchTypes.Dijkstra:
                return(new Dijkstra <Node>(graph, source, destination));

            case SearchTypes.BFS:
                return(new BFS <Node>(graph, source, destination));

            case SearchTypes.AStar:
                return(new AStar(graph, source, destination));

            default:
                throw new Exception();
            }
        }
Exemplo n.º 15
0
    /*public static void FindPath<NodeType>(
     *      WeightedGraph<NodeType> graph,
     *      NodeType startNode, NodeType endNode,
     *      List<NodeType> outputPath, int maxiterations = 1000)
     * {
     *
     *  LinkedList<NodeType> visited = new LinkedList<NodeType>();
     *  Dictionary<NodeType, NodeType> prev = new Dictionary<NodeType, NodeType>();
     *  Dictionary<NodeType, int> distance = new Dictionary<NodeType, int>();
     *  List<NodeType> sortedNeighbours = new List<NodeType>();
     *
     *  distance.Add(startNode, 0);
     *  sortedNeighbours.Add(startNode);
     *  visited.AddLast(startNode);
     *  int i = 0;
     *
     *  while (i < maxiterations && sortedNeighbours.Count != 0)
     *  {
     *      NodeType curr = sortedNeighbours[0];
     *      Debug.Log(curr.ToString());
     *      foreach (var neighbor in graph.Neighbors(curr))
     *      {
     *          int dis = distance[curr] + graph.GetWeight(neighbor);
     *          if ((visited.Contains(neighbor) && distance[neighbor] > dis) || (!visited.Contains(neighbor)))
     *          {
     *              distance[neighbor] = dis;
     *              prev[neighbor] = curr;
     *              if (!visited.Contains(neighbor))
     *              {
     *                  insertNeighbour(sortedNeighbours, distance[neighbor], neighbor, graph);
     *              }
     *          }
     *
     *      }
     *      visited.AddFirst(curr);
     *      sortedNeighbours.RemoveAt(0);
     *      i++;
     *  }
     *  outputPath = CreatePath(prev, startNode, endNode);
     *
     * }*/

    public static List <NodeType> GetPath <NodeType>(WeightedGraph <NodeType> graph, NodeType source, NodeType dest)
    {
        List <NodeType> path = new List <NodeType>();
        Dictionary <NodeType, NodeType> route = DijekstraBuilder(graph, source);

        if (route.ContainsKey(dest))
        {
            NodeType tempD = dest;
            path.Insert(0, tempD); //

            while (!path[0].Equals(source))
            {
                //Debug.Log("END?");
                tempD = route[tempD];
                path.Insert(0, tempD);
            }
            // Debug.Log("return");
        }
        return(path);
    }
Exemplo n.º 16
0
        public override IEnumerable <object> Solve(TextReader inputStream)
        {
            var(cityCount, railwayCount, initialSilver) = inputStream.ReadValue <int, int, int>();
            const int extended = 2500;
            var       graph    = new WeightedGraph(cityCount * (extended + 1));

            for (int i = 0; i < railwayCount; i++)
            {
                var(u, v, a, b) = inputStream.ReadValue <int, int, int, int>();
                u--;
                v--;

                for (int shift = 0; shift + a <= extended; shift++)
                {
                    graph.AddEdge(new WeightedEdge(ToGraphNodeIndex(cityCount, u, shift + a), ToGraphNodeIndex(cityCount, v, shift), b));
                    graph.AddEdge(new WeightedEdge(ToGraphNodeIndex(cityCount, v, shift + a), ToGraphNodeIndex(cityCount, u, shift), b));
                }
            }

            for (int city = 0; city < cityCount; city++)
            {
                var(c, d) = inputStream.ReadValue <int, int>();
                for (int shift = 0; shift < extended; shift++)
                {
                    graph.AddEdge(new WeightedEdge(ToGraphNodeIndex(cityCount, city, shift), ToGraphNodeIndex(cityCount, city, Math.Min(shift + c, extended)), d));
                }
            }

            var dijkstra  = new Dijkstra <BasicNode, WeightedEdge>(graph);
            var distances = dijkstra.GetDistancesFrom(ToGraphNodeIndex(cityCount, 0, Math.Min(initialSilver, extended)));

            for (int city = 1; city < cityCount; city++)
            {
                var min = long.MaxValue;
                for (int silver = 0; silver <= extended; silver++)
                {
                    min = Math.Min(min, distances[ToGraphNodeIndex(cityCount, city, silver)]);
                }
                yield return(min);
            }
        }
Exemplo n.º 17
0
    private void TestWeightedGraph()
    {
        WeightedGraph grafoValorado = new WeightedGraph(5, false);

        grafoValorado.nuevoVertex("A");
        grafoValorado.nuevoVertex("B");
        grafoValorado.nuevoVertex("C");
        grafoValorado.nuevoVertex("D");
        grafoValorado.nuevoVertex("E");
        grafoValorado.nuevoArco("A", "B", 1);
        grafoValorado.nuevoArco("B", "C", 2);
        grafoValorado.nuevoArco("B", "D", 2);
        grafoValorado.nuevoArco("A", "C", 1);
        grafoValorado.nuevoArco("D", "E", 10);
        Debug.Log(grafoValorado.ToString());
        Dijkstra caminoCorto = new Dijkstra();

        string[] camino = caminoCorto.FindPath(grafoValorado, "A", "E");

        Debug.Log("Camino :" + string.Join("-> ", camino));
    }
Exemplo n.º 18
0
        public static string ToDot(this WeightedGraph g)
        {
            var builder      = new StringBuilder("graph G {\r\n");
            var visitedPairs = new List <(string, string)>();

            foreach (var edge in g.Graph.Edges)
            {
                if (visitedPairs.Contains((edge.Source, edge.Target)) ||
                    visitedPairs.Contains((edge.Target, edge.Source)))
                {
                    continue;
                }
                visitedPairs.Add((edge.Source, edge.Target));

                builder.AppendLine(
                    $"\"{edge.Source}\" -- \"{edge.Target}\" [label=\"{TimeSpan.FromMilliseconds(g.Costs[edge])}\" {(g.Answers[edge] ? "" : ",color = red")}];");
            }

            builder.AppendLine("}");
            return(builder.ToString());
        }
Exemplo n.º 19
0
        public void graphTest()
        {
            Console.WriteLine("Testing Graph:");
            List <Vertex <ReadingTag> >       tags  = new List <Vertex <ReadingTag> >();
            List <WeightedEdge <ReadingTag> > edges = new List <WeightedEdge <ReadingTag> >();

            Vertex <ReadingTag> v1 = new Vertex <ReadingTag>(new ReadingTag(1, 1, "Science"));
            Vertex <ReadingTag> v2 = new Vertex <ReadingTag>(new ReadingTag(2, 1, "Technology"));
            Vertex <ReadingTag> v3 = new Vertex <ReadingTag>(new ReadingTag(3, 1, "Neuroscience"));
            Vertex <ReadingTag> v4 = new Vertex <ReadingTag>(new ReadingTag(4, 1, "Chemistry"));
            Vertex <ReadingTag> v5 = new Vertex <ReadingTag>(new ReadingTag(5, 1, "Physics"));

            tags.Add(v1);
            tags.Add(v2);
            tags.Add(v3);
            tags.Add(v4);
            tags.Add(v5);

            WeightedEdge <ReadingTag> e1 = new WeightedEdge <ReadingTag>(v1, v2, 5);
            WeightedEdge <ReadingTag> e2 = new WeightedEdge <ReadingTag>(v1, v3, 3);
            WeightedEdge <ReadingTag> e3 = new WeightedEdge <ReadingTag>(v3, v4, 1);
            WeightedEdge <ReadingTag> e4 = new WeightedEdge <ReadingTag>(v2, v4, 5);
            WeightedEdge <ReadingTag> e5 = new WeightedEdge <ReadingTag>(v4, v5, 2);

            edges.Add(e1);
            edges.Add(e2);
            edges.Add(e3);
            edges.Add(e4);
            edges.Add(e5);

            WeightedGraph <ReadingTag>        graph = new WeightedGraph <ReadingTag>(tags, edges);
            List <WeightedEdge <ReadingTag> > list  = graph.TagFinder(v1, new List <WeightedEdge <ReadingTag> >(), new List <Vertex <ReadingTag> >(), new List <Vertex <ReadingTag> >(), new List <WeightedEdge <ReadingTag> >());

            Console.WriteLine(list.Count());
            Console.WriteLine(list);
            foreach (WeightedEdge <ReadingTag> e in list)
            {
                Console.WriteLine(e.ToString());
            }
        }
Exemplo n.º 20
0
        public void FindShortestPathTest_IsolatedVertex_NullExpected()
        {
            List <Vertex> verticles = new List <Vertex>()
            {
                new Vertex()
                {
                    Id = 0, Nodes = new List <Node>()
                    {
                        new Node()
                        {
                            Weight = 1, Connectable = 1
                        }
                    }
                },

                new Vertex()
                {
                    Id = 1, Nodes = new List <Node>()
                    {
                        new Node()
                        {
                            Weight = 3, Connectable = 0
                        }
                    }
                },

                new Vertex()
                {
                    Id = 2
                }
            };

            AdjacencyList adjacencyList = new AdjacencyList(verticles);

            WeightedGraph weightedGraph = new WeightedGraph(adjacencyList);

            List <int> actual = weightedGraph.FindShortestPath(verticles[0].Id, verticles[2].Id);

            Assert.Null(actual);
        }
Exemplo n.º 21
0
        public BFSSearch(WeightedGraph <Location> graph, Location start, Location goal)
        {
            var frontier = new PriorityQueueBFS <Location>();

            frontier.Enqueue(start, 0);

            cameFrom[start]  = start;
            costSoFar[start] = 0;

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

                if (current.Equals(goal))
                {
                    break;
                }

                foreach (var next in graph.Neighbors(current))
                {
                    if (!cameFrom.ContainsKey(next))
                    {
                        double priority = 0;
                        frontier.Enqueue(next, priority);
                        cameFrom[next] = current;
                    }
                    //double newCost = costSoFar[current]
                    //    + graph.Cost(current, next);
                    //if (!costSoFar.ContainsKey(next)
                    //    || newCost < costSoFar[next])
                    //{
                    //    costSoFar[next] = newCost;
                    //    double priority = newCost + Heuristic(next, goal);
                    //    frontier.Enqueue(next, priority);
                    //    cameFrom[next] = current;
                    //}
                }
            }
        }
Exemplo n.º 22
0
        public LazyPrim(WeightedGraph G)
        {
            var V = G.V();

            marked = new bool[V];
            pq     = new MinPQ <Edge>();

            var s = 0;

            foreach (var e in G.adj(s))
            {
                pq.Enqueue(e);
            }

            mst = new List <Edge>();

            while (!pq.IsEmpty && mst.Count < V - 1)
            {
                var e = pq.DelMin();
                var v = e.either();
                var w = e.other(v);

                if (marked[v] && marked[w])
                {
                    continue;
                }

                mst.Add(e);

                if (!marked[v])
                {
                    visit(G, v);
                }
                if (!marked[w])
                {
                    visit(G, w);
                }
            }
        }
Exemplo n.º 23
0
        public override IEnumerable <object> Solve(TextReader inputStream)
        {
            var(citiesCount, roadsCount, tankCapacity) = inputStream.ReadValue <int, int, int>();
            var roadGraph = new WeightedGraph(citiesCount);

            for (int i = 0; i < roadsCount; i++)
            {
                var(a, b, fuel) = inputStream.ReadValue <int, int, int>();
                a--;
                b--;
                roadGraph.AddEdge(new WeightedEdge(a, b, fuel));
                roadGraph.AddEdge(new WeightedEdge(b, a, fuel));
            }

            var distanceWarshallFloyd = new WarshallFloyd <BasicNode, WeightedEdge>(roadGraph);
            var distances             = distanceWarshallFloyd.GetDistances();

            // こっちの初期化手法はあまり使わないか……
            var refuelEdges = Enumerable.Range(0, citiesCount)
                              .SelectMany(from => Enumerable.Range(0, citiesCount)
                                          .Select(to => new { from, to })
                                          .Where(pair => distances[pair.from, pair.to] <= tankCapacity)
                                          .Select(pair => new WeightedEdge(pair.from, pair.to)));
            var refuelGraph         = new WeightedGraph(citiesCount, refuelEdges);
            var refuelWarshallFloyd = new WarshallFloyd <BasicNode, WeightedEdge>(refuelGraph);
            var refuelCounts        = refuelWarshallFloyd.GetDistances();

            var queries = inputStream.ReadInt();

            for (int q = 0; q < queries; q++)
            {
                var(from, to) = inputStream.ReadValue <int, int>();
                from--;
                to--;
                var refuelCount = refuelCounts[from, to];
                var output      = refuelCount < long.MaxValue ? (refuelCount - 1).ToString() : (-1).ToString();
            }
            yield return(string.Empty);
        }
Exemplo n.º 24
0
        private static WeightedGraph generateGraphFromFile()
        {
            bool head = true; int edges = -1;

            foreach (var line in System.IO.File.ReadLines(@"Resources\ShortestPath01.txt"))
            {
                string[] nums = line.Split(' ');
                if (head)
                {
                    graph = new SparseGraph(Convert.ToInt32(nums[0]), false);
                    // graph = new DenseGraph(Convert.ToInt32(nums[0]), false);
                    edges = Convert.ToInt32(nums[1]);
                    head  = false;
                }
                else
                {
                    graph.AddEdge(Convert.ToInt32(nums[0]), Convert.ToInt32(nums[1]), Convert.ToDouble(nums[2]));
                }
            }
            Assert.IsTrue(graph.E() == edges);
            return(graph);
        }
Exemplo n.º 25
0
        public void testWeightedAddVertex()
        {
            WeightedGraph<int> graph = new WeightedGraph<int>();
            int num1 = 1;
            int num2 = 2;
            int num3 = 3;
            int num4 = 4;
            int num5 = 5;

            graph.addVertex(num1);
            graph.addVertex(num2);
            graph.addVertex(num3);
            graph.addVertex(num4);
            graph.addVertex(num5);

            Assert.IsTrue(graph.numVertices == 5);
            Assert.IsTrue(graph.AdjacencyList.ContainsKey(num1));
            Assert.IsTrue(graph.AdjacencyList.ContainsKey(num2));
            Assert.IsTrue(graph.AdjacencyList.ContainsKey(num3));
            Assert.IsTrue(graph.AdjacencyList.ContainsKey(num4));
            Assert.IsTrue(graph.AdjacencyList.ContainsKey(num5));
        }
Exemplo n.º 26
0
            public D3JsGraph(WeightedGraph<string> graph)
            {
                foreach(var vertex in graph.Vertices)
                {
                    this._nodes.Add(new Node(vertex));
                }

                foreach(var edge in graph.WeightedEdges)
                {
                    var link = new Link()
                    {
                       source = _nodes.FindIndex(node => {
                           return node.name == edge.Start;
                       }),
                       target = _nodes.FindIndex(node => {
                           return node.name == edge.End;
                       }),
                       value = edge.Weight
                    };
                    this._links.Add(link);
                }
            }
Exemplo n.º 27
0
        public override IEnumerable <object> Solve(TextReader inputStream)
        {
            const long startYen = 1_000_000_000_000_000;

            var(citiesCount, trainsCount, start, terminal) = inputStream.ReadValue <int, int, int, int>();
            start--;
            terminal--;

            var yenGraph   = new WeightedGraph(citiesCount);
            var snuukGraph = new WeightedGraph(citiesCount);

            for (int i = 0; i < trainsCount; i++)
            {
                var(from, to, yen, snuuk) = inputStream.ReadValue <int, int, long, long>();
                from--;
                to--;
                yenGraph.AddEdge(new WeightedEdge(from, to, yen));
                yenGraph.AddEdge(new WeightedEdge(to, from, yen));
                snuukGraph.AddEdge(new WeightedEdge(from, to, snuuk));
                snuukGraph.AddEdge(new WeightedEdge(to, from, snuuk));
            }

            var yenFares   = new Dijkstra <BasicNode, WeightedEdge>(yenGraph).GetDistancesFrom(new BasicNode(start));
            var snuukFares = new Dijkstra <BasicNode, WeightedEdge>(snuukGraph).GetDistancesFrom(new BasicNode(terminal));

            var remainedSnuuks = new Stack <long>(citiesCount);

            for (int exchange = citiesCount - 1; exchange >= 0; exchange--)
            {
                var best = remainedSnuuks.Count > 0 ? remainedSnuuks.Peek() : int.MinValue;
                var next = startYen - (yenFares[exchange] + snuukFares[exchange]);
                remainedSnuuks.Push(Math.Max(best, next));
            }

            foreach (var remainedSnuuk in remainedSnuuks)
            {
                yield return(remainedSnuuk);
            }
        }
Exemplo n.º 28
0
        public void TestUndirectedUnion()
        {
            var addition = new WeightedGraph <Char>();

            var a = new CharWeightedNode('A');
            var c = new CharWeightedNode('C');
            var f = new CharWeightedNode('F');
            var h = new CharWeightedNode('H');

            addition.AddNode(a);
            addition.AddNode(c);
            addition.AddNode(f);
            addition.AddNode(h);

            addition.AddUndirectedEdge(a, c, 11);
            addition.AddUndirectedEdge(a, h, 7);
            addition.AddUndirectedEdge(c, h, 14);

            var graph = MockWeightedGraph();

            graph.UndirectedUnion(addition);

            var bfs = "";

            graph.BFS(node => bfs += node.Content);
            Assert.AreEqual("ABECHDGF", bfs);

            var edges  = graph.UndirectedEdges();
            var actual = $"{edges.Length} edges";

            foreach (var edge in edges)
            {
                actual += $", {edge.Item1.Content.ToString()}-{edge.Item3.ToString()}-{edge.Item2.Content.ToString()}";
            }
            var expected = "10 edges, A-20-B, A-8-E, A-11-C, A-7-H, B-18-C, B-21-D, C-15-D, C-30-E, C-14-H, D-12-E";

            Assert.AreEqual(expected, actual);
        }
Exemplo n.º 29
0
        private static void ProcessData()
        {
            Console.WriteLine("Загрузка результатов вопросов...");
            var files =
                Directory.GetFiles(
                    Directory.GetCurrentDirectory(),
                    "TR_*.json", SearchOption.TopDirectoryOnly);
            var testResults = files
                              .Select(BaseHelper.LoadJson <TestResult>)
                              .ToList();

            var combinedResult = new TestResult();

            foreach (var text in testResults.SelectMany(tr => tr.Result.Questions).Select(q => q.Text))
            {
                var questions = testResults
                                .SelectMany(tr => tr.Result.Questions)
                                .Where(q => q.Text == text && q.AnswerTime.HasValue)
                                .ToArray();

                var timings = questions
                              .Select(q => q.AnswerTime.Value.TotalMilliseconds)
                              .ToArray();

                var average = timings.Average();
                var sumOfSquaresOfDifferences = timings
                                                .Select(val => (val - average) * (val - average))
                                                .Sum();
                var sd = Math
                         .Sqrt(sumOfSquaresOfDifferences / timings.Length);
                combinedResult.AddQuestion(new Question(questions.First(), TimeSpan.FromMilliseconds(average), sd));
            }

            combinedResult.SaveJson($"PR_{DateTime.Now:yyyy-dd-M--HH-mm-ss}.json");
            var graph = WeightedGraph.FromTestResult(combinedResult);

            File.WriteAllText($"PR_{DateTime.Now:yyyy-dd-M--HH-mm-ss}.dot", graph.ToDot());
        }
Exemplo n.º 30
0
        public IGraph<string> WeightedGraphOfSendersAndRecipients()
        {
            var graph = new WeightedGraph<string>();
                foreach (var email in this.Data.AllEmails)
                {
                    if (string.IsNullOrWhiteSpace(email.Sender))
                    {
                        continue;
                    }

                    foreach (var recipient in email.Recipients)
                    {
                        if (string.IsNullOrWhiteSpace(recipient))
                        {
                            continue;
                        }

                        graph.Connect(email.Sender, recipient);
                    }
                }

                return graph;
        }
Exemplo n.º 31
0
        public EagerPrim(WeightedGraph G)
        {
            int V = G.V();

            pq = new IndexMinPQ <Edge>(V);

            marked = new bool[V];

            Visit(G, 0);

            path = new List <Edge>();

            while (!pq.IsEmpty)
            {
                var e = pq.MinKey();
                var v = pq.DelMin();
                path.Add(e);
                if (!marked[v])
                {
                    Visit(G, v);
                }
            }
        }
Exemplo n.º 32
0
        public static WeightedGraph edgeWeightedGraph()
        {
            var g = new WeightedGraph(8);

            g.addEdge(new Edge(0, 7, 0.16));
            g.addEdge(new Edge(2, 3, 0.17));
            g.addEdge(new Edge(1, 7, 0.19));
            g.addEdge(new Edge(0, 2, 0.26));
            g.addEdge(new Edge(5, 7, 0.28));
            g.addEdge(new Edge(1, 3, 0.29));
            g.addEdge(new Edge(1, 5, 0.32));
            g.addEdge(new Edge(2, 7, 0.34));
            g.addEdge(new Edge(4, 5, 0.35));
            g.addEdge(new Edge(1, 2, 0.36));
            g.addEdge(new Edge(4, 7, 0.37));
            g.addEdge(new Edge(0, 4, 0.38));
            g.addEdge(new Edge(6, 2, 0.4));
            g.addEdge(new Edge(3, 6, 0.52));
            g.addEdge(new Edge(6, 0, 0.58));
            g.addEdge(new Edge(6, 4, 0.93));

            return(g);
        }
Exemplo n.º 33
0
        static void Main(string[] args)
        {
            var graph = new WeightedGraph();

            graph.addVertex("A");
            graph.addVertex("B");
            graph.addVertex("C");
            graph.addVertex("D");
            graph.addVertex("E");
            graph.addVertex("F");

            graph.addEdge("A", "B", 4);
            graph.addEdge("A", "C", 2);
            graph.addEdge("B", "E", 3);
            graph.addEdge("C", "D", 2);
            graph.addEdge("C", "F", 4);
            graph.addEdge("D", "E", 3);
            graph.addEdge("D", "F", 1);
            graph.addEdge("E", "F", 1);

            var result = graph.Dijkstra("A", "E");

            Console.WriteLine(123);
        }
Exemplo n.º 34
0
        public static void Start()
        {
            graph = new WeightedGraph(false);
            graph.Add('w', 'x', 6);
            graph.Add('w', 'y', 1);
            graph.Add('w', 'z', 3);
            graph.Add('x', 'y', 4);
            graph.Add('x', 'z', 3);
            graph.Add('y', 'z', 2);

            int min = int.MaxValue;

            for (int i = 0; i < graph.VerticeCount; i++)
            {
                var vertex   = graph.Vertices[i];
                var visited  = "" + vertex;
                var distance = GetDistance(vertex, graph.VerticeCount - 1, visited, 0);
                if (distance < min)
                {
                    min = distance;
                }
            }
            Console.WriteLine(min);
        }
Exemplo n.º 35
0
        public override IEnumerable <object> Solve(TextReader inputStream)
        {
            var(townCount, pathCount, timeLimit) = inputStream.ReadValue <int, int, int>();
            var gainRates    = inputStream.ReadLongArray();
            var goingGraph   = new WeightedGraph(townCount);
            var backingGraph = new WeightedGraph(townCount);

            for (int i = 0; i < pathCount; i++)
            {
                var(from, to, distance) = inputStream.ReadValue <int, int, int>();
                from--;
                to--;
                goingGraph.AddEdge(new WeightedEdge(from, to, distance));
                backingGraph.AddEdge(new WeightedEdge(to, from, distance));
            }

            var goingDijkstra    = new Dijkstra <BasicNode, WeightedEdge>(goingGraph);
            var backingDijkstra  = new Dijkstra <BasicNode, WeightedEdge>(backingGraph);
            var goingDistances   = goingDijkstra.GetDistancesFrom(new BasicNode(0));
            var backingDistances = backingDijkstra.GetDistancesFrom(new BasicNode(0));

            const long inf = 1L << 50;
            long       max = 0;

            for (int i = 0; i < townCount; i++)
            {
                if (goingDistances[i] > inf || backingDistances[i] > inf)
                {
                    continue;
                }
                var earned = gainRates[i] * (timeLimit - goingDistances[i] - backingDistances[i]);
                max = Math.Max(max, earned);
            }

            yield return(max);
        }
Exemplo n.º 36
0
        public AStarSearch(WeightedGraph <Location> graph, Location start, Location goal)
        {
            var frontier = new PriorityQueue <Location>();

            // kk = frontier;
            frontier.Enqueue(start, 0);

            cameFrom[start]  = start;
            costSoFar[start] = 0;

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

                if (current.Equals(goal))
                {
                    break;
                }

                foreach (var next in graph.Neighbors(current))
                {
                    double newCost = costSoFar[current]
                                     + graph.Cost(current, next);
                    if (!costSoFar.ContainsKey(next) ||
                        newCost < costSoFar[next])
                    {
                        costSoFar[next] = newCost;
                        double priority = newCost + Heuristic(next, goal);
                        frontier.Enqueue(next, priority);
                        cameFrom[next] = current;

                        Debug.Log("xx-- from " + current + " to " + next);
                    }
                }
            }
        }
Exemplo n.º 37
0
        public void testWeightedRemoveEdge()
        {
            WeightedGraph<int> graph = new WeightedGraph<int>();
            int num1 = 1;
            int num2 = 2;
            int num3 = 3;
            int num4 = 4;
            int num5 = 5;

            graph.addEdge(num1, num2);
            graph.addEdge(num2, num3);
            graph.addEdge(num3, num4);
            graph.addEdge(num4, num5);
            graph.addEdge(num1, num3);

            graph.deleteEdge(num1, num2);
            graph.deleteEdge(num1, num3);

            Assert.IsTrue(graph.AdjacencyList[num1].Count ==0);
            Assert.IsTrue(graph.AdjacencyList[num2].Count == 1);
            Assert.IsTrue(graph.AdjacencyList[num3].Count == 2);
            Assert.IsTrue(graph.AdjacencyList[num4].Count == 2);
            Assert.IsTrue(graph.AdjacencyList[num5].Count == 1);
        }
Exemplo n.º 38
0
        public List <AllPairShortestPathResult <T, W> > GetAllPairShortestPaths(WeightedGraph <T, W> graph)
        {
            //we need this vertex array index for generics
            //since array indices are int and T is unknown type
            var vertexIndex        = new Dictionary <int, T>();
            var reverseVertexIndex = new Dictionary <T, int>();
            var i = 0;

            foreach (var vertex in graph.Vertices)
            {
                vertexIndex.Add(i, vertex.Key);
                reverseVertexIndex.Add(vertex.Key, i);
                i++;
            }

            //init all distance to default Weight
            var result = new W[graph.Vertices.Count, graph.Vertices.Count];
            //to trace the path
            var parent = new T[graph.Vertices.Count, graph.Vertices.Count];

            for (i = 0; i < graph.VerticesCount; i++)
            {
                for (int j = 0; j < graph.VerticesCount; j++)
                {
                    result[i, j] = operators.MaxValue;
                }
            }

            for (i = 0; i < graph.VerticesCount; i++)
            {
                result[i, i] = operators.DefaultValue;
            }
            //now set the known edge weights to neighbours
            for (i = 0; i < graph.VerticesCount; i++)
            {
                foreach (var edge in graph.Vertices[vertexIndex[i]].Edges)
                {
                    result[i, reverseVertexIndex[edge.Key.Value]] = edge.Value;
                    parent[i, reverseVertexIndex[edge.Key.Value]] = graph.Vertices[vertexIndex[i]].Value;

                    result[reverseVertexIndex[edge.Key.Value], i] = edge.Value;
                    parent[reverseVertexIndex[edge.Key.Value], i] = edge.Key.Value;
                }
            }

            //here is the meat of this algorithm
            //if we can reach node i to j via node k and if it is shorter pick that Distance
            for (int k = 0; k < graph.VerticesCount; k++)
            {
                for (i = 0; i < graph.VerticesCount; i++)
                {
                    for (int j = 0; j < graph.VerticesCount; j++)
                    {
                        //no path
                        if (result[i, k].Equals(operators.MaxValue) ||
                            result[k, j].Equals(operators.MaxValue))
                        {
                            continue;
                        }

                        var sum = operators.Sum(result[i, k], result[k, j]);

                        if (sum.CompareTo(result[i, j]) >= 0)
                        {
                            continue;
                        }

                        result[i, j] = sum;
                        parent[i, j] = parent[k, j];
                    }
                }
            }

            //trace path
            var finalResult = new List <AllPairShortestPathResult <T, W> >();

            for (i = 0; i < graph.VerticesCount; i++)
            {
                for (int j = 0; j < graph.VerticesCount; j++)
                {
                    var source   = vertexIndex[i];
                    var dest     = vertexIndex[j];
                    var distance = result[i, j];
                    var path     = tracePath(result, parent, i, j, vertexIndex, reverseVertexIndex);

                    finalResult.Add(new AllPairShortestPathResult <T, W>(source, dest, distance, path));
                }
            }

            return(finalResult);
        }
Exemplo n.º 39
0
        public void testWeightedRemoveVertex()
        {
            WeightedGraph<int> graph = new WeightedGraph<int>();
            int num1 = 1;
            int num2 = 2;
            int num3 = 3;
            int num4 = 4;
            int num5 = 5;

            graph.addEdge(num1, num2);
            graph.addEdge(num2, num3);
            graph.addEdge(num3, num4);
            graph.addEdge(num4, num5);
            graph.addEdge(num1, num3);
            GraphNode<int> node = new GraphNode<int>(num1);

            graph.deleteVertex(num1);
            graph.deleteVertex(num4);
            Assert.IsFalse(graph.AdjacencyList.ContainsKey(num1));
            Assert.IsFalse(graph.AdjacencyList.ContainsKey(num4));
            Assert.IsTrue(graph.numVertices == 3);
            Assert.IsFalse(graph.AdjacencyList[num2].Contains(node));
        }
Exemplo n.º 40
0
        /// <summary>
        /// Spawns the features.
        /// </summary>
        /// <param name="previous">Previous maze graph.</param>
        /// <param name="next">Next maze graph.</param>
        public void SpawnFeatures(WeightedGraph<MazeCell, MazeCellEdgeWeight> previous = null,
            WeightedGraph<MazeCell, MazeCellEdgeWeight> next = null)
        {
            if (!IsInitialized)
            {
                Logger.Log.AddLogEntry(LogLevel.Error, "Maze", "Cannot place features as maze is not initialized!");
                return;
            }

            if (!IsGenerated)
            {
                Logger.Log.AddLogEntry(LogLevel.Error, "Maze", "Cannot place features as maze is not generated!");
                return;
            }

            if (AreFeaturesPlaced)
            {
                Logger.Log.AddLogEntry(LogLevel.Warning, "Maze", "Features are already placed in this maze!");
                return;
            }

            if (placeFeaturesDelegate != null)
            {
                AreFeaturesPlaced = true;
                placeFeaturesDelegate (previous, graph, next, rand, PortalSpawnFactor);
            }
            else
            {
                Logger.Log.AddLogEntry(LogLevel.Error, "Maze", "Failed to place features as placing delegate is null!");
            }
        }
Exemplo n.º 41
0
 public void testWeightedCreation()
 {
     WeightedGraph<int> graph = new WeightedGraph<int>();
     Assert.AreNotEqual(graph, null);
     Assert.IsFalse(graph.Directed);
 }