Exemplo n.º 1
0
        public void DoubleTree(Graph graph)
        {
            MST mst = kruskal(graph);

            double min = Double.MaxValue;

            foreach (Node node in mst.nodeList)
            {
                List <Node> eulerTour = new List <Node>();
                DFS(node, eulerTour);

                double result = lengthFromEulerTour(eulerTour, graph);

                Console.Write(string.Join(",", eulerTour));
                Console.WriteLine(" weight :" + Math.Round(result, 2));

                if (result < min)
                {
                    min = result;
                }

                mst.reset();
            }

            Console.WriteLine("minimal:" + Math.Round(min, 2));
        }
Exemplo n.º 2
0
        public void KruskalTests()
        {
            Console.WriteLine("===Kruskal MST search implementation on graphs===");
            int minWeight = MST.Kruskal_MST(graph);

            Console.WriteLine($"Weight of spanningTree: {minWeight}");
        }
Exemplo n.º 3
0
 private void Init()
 {
     foreach (var v in graph.Vertices)
     {
         MST.AddVertex(v);
     }
 }
Exemplo n.º 4
0
        public void PrimTests()
        {
            Console.WriteLine("===Prim MST search implementation on graphs===");
            int minWeight = MST.Prim_MST(graph);

            Console.WriteLine($"Weight of spanningTree: {minWeight}");
        }
Exemplo n.º 5
0
        static int RunMST(StreamReader input)
        {
            string[] s = input.ReadLine().Split(' ');
            int      n = Int32.Parse(s[0]);
            int      m = Int32.Parse(s[1]);

            double[][] g = new double[n][];
            for (int i = 0; i < n; ++i)
            {
                g[i] = new double[n];
                for (int j = 0; j < n; ++j)
                {
                    g[i][j] = MST.Inf;
                }
            }

            for (int i = 0; i < m; ++i)
            {
                s = input.ReadLine().Split(' ');
                int x = Int32.Parse(s[0]) - 1,
                    y = Int32.Parse(s[1]) - 1,
                    w = Int32.Parse(s[2]);
                g[x][y] = w;
                g[y][x] = w;
            }

            MSTResults res = MST.FindMST(g);

            return(Convert.ToInt32(res.Weight));
        }
        // Prim's MST
        public override void GenerateMST()
        {
            Init();

            for (int i = 0; i < graph.Size; i++)
            {
                int v           = FindMinimumDistance();
                var newDistance = distance[v];
                if (newDistance < INFINITY)
                {
                    componentOfMST[v] = true;

                    var v1   = graph.GetVertexByID((uint)v);
                    var v2   = neighbor[v];
                    var edge = new Edge <V, int>(v1, v2);
                    MST.AddEdge(edge);

                    foreach (var w in graph.GetNeighbours(v1))
                    {
                        var e2 = graph.GetEdge(v1, w);
                        if (!componentOfMST[w.ID] && e2.Value < distance[w.ID])
                        {
                            distance[w.ID] = e2.Value;
                            neighbor[w.ID] = v1;
                        }
                    }
                }
                else
                {
                    break;
                }
            }
        }
    public void Generate()
    {
        InstancedTiles      = new GameObject[size, size];
        DungeonTerrainTiles = new DungeonTerrainTile[size, size];
        Rooms = new List <Room>();

        for (int i = 0; i < attempts; i++)
        {
            CreateRoom(roomSize.x, roomSize.y);
        }

        mesh = DelaunayTriangulation.TriangulatePoints(centerWorldTiles);
        spanningTree.AddRange(MST.FormTree(mesh, centerWorldTiles.Count, generateExtraEdges));

        for (int i = 0; i < spanningTree.Count; i++)
        {
            CreatePaths(spanningTree[i].edge);
        }
        onComplete?.Invoke();

        if (instantiateDebugTiles)
        {
            InstantiateTiles();
        }
    }
Exemplo n.º 8
0
    void find_MST()
    {
        MST spanningTree = new MST();

        spanningTree.SetV(AllStayingRooms.Count);

        int[,] graph = graph_Gen();

        ansMST = spanningTree.runMST(graph);

        //draws line connections

        /*
         * for (int i = 1; i < AllStayingRooms.Count; i++)
         * {
         *  Transform pos1 = stayingRoomArray[i].room.transform;
         *  Transform pos2 = stayingRoomArray[ansMST[i, 0]].room.transform;
         *
         *  Debug.DrawLine(new Vector3(pos1.position.x, pos1.position.y, pos1.position.z),
         *      new Vector3(pos2.position.x, pos2.position.y, pos2.position.z), Color.green, 2000f, true);
         * }
         */
        //createPath(ansMSt);
        MSTDone = true;
        buildPaths();
        //buildWalls();
    }
        public double CalcMST(Point start)
        {
            int processCount = PointCount - 1;

            start.Dist = 0;
            Point        currentPoint = start;
            List <Point> process      = new List <Point>();

            while (processCount > 0)
            {
                Relax(currentPoint);
                currentPoint.Check = true;
                foreach (var p in currentPoint.ConnectedPoints)
                {
                    if (!p.Check && !p.IsInQueue)
                    {
                        process.Add(p);
                        p.IsInQueue = true;
                    }
                }
                var minKey = process.OrderBy(x => x.Dist).FirstOrDefault();
                if (minKey != null)
                {
                    MST.Add(CalcDistance(minKey, minKey.Prev));
                    process.Remove(minKey);
                    currentPoint = minKey;
                }
                processCount--;
            }
            return(Math.Round(MST.Sum(), 6));
        }
Exemplo n.º 10
0
        protected override void FinishLevelSetup()
        {
            // create vertices from settlement objects
            var vertices = m_settlements.Select(go => new Vertex(go.Pos));

            // calculate MST
            m_goalgraph = MST.MinimumSpanningTree(vertices);
        }
Exemplo n.º 11
0
 public void UpdateTime()
 {
     ustDateTime = nServerTime.GetCurrentServerTime();
     PST.UpdateZoneTime(ustDateTime);
     MST.UpdateZoneTime(ustDateTime);
     CST.UpdateZoneTime(ustDateTime);
     EST.UpdateZoneTime(ustDateTime);
     CurrVSServ.updateTime(ustDateTime);
 }
        public void MSTWeightTest()
        {
            var mst            = MST.MinimumSpanningTree(m_level2pos);
            var level2vertices = mst.Vertices.ToList();
            var cost           = new Edge(level2vertices[0], level2vertices[1]).Weight +
                                 new Edge(level2vertices[2], level2vertices[1]).Weight +
                                 new Edge(level2vertices[2], level2vertices[3]).Weight +
                                 new Edge(level2vertices[3], level2vertices[4]).Weight;

            Assert.AreEqual(cost, mst.TotalEdgeWeight, MathUtil.EPS);
        }
Exemplo n.º 13
0
        public void TestKruskMST()
        {
            MST mst = graph.KruskMST();

            Edge[] edges = mst.Edges();
            foreach (Edge edge in edges)
            {
                // TestContext.WriteLine(edge.ToString());
            }
            TestContext.WriteLine(mst.Weight().ToString());
        }
Exemplo n.º 14
0
        public void TestMST()
        {
            MST mst = new MST();

            mst.AddEdge(1, 2, 1);
            mst.AddEdge(1, 3, 3);
            mst.AddEdge(1, 4, 4);
            mst.AddEdge(2, 3, 2);
            mst.AddEdge(3, 4, 5);
            mst.Execute();
            Assert.AreEqual(7, mst.Cost);
        }
Exemplo n.º 15
0
        private void Init()
        {
            componentOfMST = new bool[graph.Size];
            queue          = new PriorityQueue <IEdge <V, int> >((a, b) => a.Value - b.Value);

            foreach (var v in graph.Vertices)
            {
                MST.AddVertex(v);
            }

            Visit(source);
        }
Exemplo n.º 16
0
        // Kruskal's MST

        /*
         * 1. Sort edges by decresing weight
         * 2. Pick the first edge with lowest weight
         * 3. Detect cycle
         * 4. Add to graph if not cycle
         */
        public override void GenerateMST()
        {
            var edgeEnum = graph.Edges.OrderBy(e => e.Value);

            foreach (var nextEdge in edgeEnum)
            {
                var isCycle = unionFind.IsCycle((int)nextEdge.Start.ID, (int)nextEdge.End.ID);
                if (!isCycle)
                {
                    MST.AddEdge(nextEdge);
                }
            }
        }
Exemplo n.º 17
0
 private void Run()
 {
     if (_Root == null)
     {
         InvokeRuntimeValidationError(new List <ErrorWithPath>(1)
         {
             new ErrorWithPath(null, "Model System Root not found", "The model system was not processed properly and then run!")
         });
         return;
     }
     if (ValidateModelSystem())
     {
         try
         {
             SetupRunDirectory();
             if (!ValidateRuntimeModelSystem())
             {
                 // The call will already signal the errors.
                 return;
             }
             _Root.Save(Path.Combine(RunDirectory, "RunParameters.xml"));
             ModelSystemStructureModelRoot = new ModelSystemStructureModel(null, _Root);
             MST.Start();
             InvokeRunCompleted();
         }
         catch (ThreadAbortException)
         {
             // This is fine just continue
         }
         catch (Exception e)
         {
             GetInnermostError(ref e);
             List <int> path       = null;
             string     moduleName = null;
             if (e is XTMFRuntimeException runtimeError)
             {
                 if (runtimeError.Module != null)
                 {
                     path       = GetModulePath(runtimeError.Module);
                     moduleName = runtimeError.Module.Name;
                 }
                 else
                 {
                     path       = null;
                     moduleName = "Null Module";
                 }
             }
             InvokeRuntimeError(new ErrorWithPath(path, e.Message, e.StackTrace, moduleName, e));
         }
     }
 }
        public void Level2MSTTest()
        {
            var level2mst = MST.MinimumSpanningTree(m_level2pos);

            var expected       = new AdjacencyListGraph(m_level2pos);
            var level2vertices = expected.Vertices.ToList();

            for (int i = 0; i < level2vertices.Count - 1; i++)
            {
                expected.AddEdge(level2vertices[i], level2vertices[i + 1]);
            }

            Assert.True(expected.Equals(level2mst));
        }
        public void ContainsEdgeTest()
        {
            var level2mst = MST.MinimumSpanningTree(m_level2pos);

            var level2vertices = level2mst.Vertices.ToList();

            Assert.True(level2mst.ContainsEdge(level2vertices[0], level2vertices[1]));
            Assert.True(level2mst.ContainsEdge(level2vertices[2], level2vertices[1]));
            Assert.True(level2mst.ContainsEdge(level2vertices[2], level2vertices[3]));
            Assert.True(level2mst.ContainsEdge(level2vertices[3], level2vertices[4]));

            Assert.False(level2mst.ContainsEdge(level2vertices[0], level2vertices[2]));
            Assert.False(level2mst.ContainsEdge(level2vertices[3], level2vertices[1]));
            Assert.False(level2mst.ContainsEdge(level2vertices[4], level2vertices[1]));
            Assert.False(level2mst.ContainsEdge(level2vertices[4], level2vertices[2]));
            Assert.False(level2mst.ContainsEdge(level2vertices[1], level2vertices[3]));
        }
        private void Init()
        {
            queue = new PriorityQueue <IEdge <V, int> >();

            for (int i = 0; i < graph.Size; i++)
            {
                componentOfMST[i] = false;
                distTo[i]         = INFINITY;
            }

            foreach (var v in graph.Vertices)
            {
                MST.AddVertex(v);
            }

            Visit(source);
        }
Exemplo n.º 21
0
        static void Main(string[] args)
        {
            var    mst = new MST();
            string line;

            using (StreamReader srStreamRdr = new StreamReader(@"edges.txt"))
            {
                while ((line = srStreamRdr.ReadLine()) != null)
                {
                    string[] values = line.Split(new Char[] { ' ' });
                    mst.AddEdge(int.Parse(values[0]), int.Parse(values[1]), int.Parse(values[2]));
                }
            }
            mst.Execute();
            Console.WriteLine(mst.Cost);
            Console.ReadKey();
        }
        // Prim's MST
        public override void GenerateMST()
        {
            Init();

            while (!queue.Empty)
            {
                var e = queue.Dequeue();

                var v = e.Start;
                var w = e.End;
                if (componentOfMST[v.ID] && componentOfMST[w.ID])
                {
                    continue;
                }
                MST.AddEdge(e);
                Visit(v);
                Visit(w);
            }
        }
        private void Init()
        {
            for (int i = 0; i < graph.Size; i++)
            {
                componentOfMST[i] = false;
                neighbor[i]       = source;
                distance[i]       = INFINITY;
            }

            foreach (var v in graph.GetNeighbours(source))
            {
                distance[v.ID] = graph.GetEdge(source, v).Value;
            }

            foreach (var v in graph.Vertices)
            {
                MST.AddVertex(v);
            }

            componentOfMST[source.ID] = true;
        }
Exemplo n.º 24
0
    private Graph <int> SpanningTree(List <Triangle> triangleList)
    {
        // Generate graph from triangle list.
        // The context of a node in the graph holds the value of the id in a triangle's vertex.
        // And the weight of an edge is the distance between to centers.
        Graph <int> graph = new Graph <int>(mainRoomList.ConvertAll <int>(n => n.id));

        for (int i = 0; i < triangleList.Count; i++)
        {
            graph.AddEdge(triangleList[i].v1.id, triangleList[i].v2.id, Vector2.Distance(triangleList[i].v1.position, triangleList[i].v2.position));
            graph.AddEdge(triangleList[i].v2.id, triangleList[i].v3.id, Vector2.Distance(triangleList[i].v2.position, triangleList[i].v3.position));
            graph.AddEdge(triangleList[i].v3.id, triangleList[i].v1.id, Vector2.Distance(triangleList[i].v3.position, triangleList[i].v1.position));
        }

        MST <int>   mst      = new MST <int>();
        Graph <int> mstGraph = mst.Prim(graph);

        ///
        DrawSpanningTree(mstGraph);

        return(mstGraph);
    }
        private void ClearPressed(object sender, RoutedEventArgs e)
        {
            // clsGraph mine = new clsGraph(4);
            // mine.AddEdge(0, 1);
            // mine.AddEdge(0, 2);
            // mine.AddEdge(1, 2);
            // mine.AddEdge(2, 0);
            // mine.AddEdge(2, 3);
            // mine.AddEdge(3, 3);
            //
            // mine.PrintAdjacencyMatrix();
            // mine.DFS(2);

            MST mine2 = new MST(5);

            int[,] graph = new int[, ] {
                { 0, 2, 0, 6, 0 },
                { 2, 0, 3, 8, 5 },
                { 0, 3, 0, 0, 7 },
                { 6, 8, 0, 0, 9 },
                { 0, 5, 7, 9, 0 }
            };
            mine2.primMST(graph);
        }
Exemplo n.º 26
0
 public override string PollStatusMessage() => MST?.ToString() ?? "No MST";
Exemplo n.º 27
0
        /// <summary>
        /// Prints the item report
        /// </summary>
        /// <returns>The item report</returns>
        public override string ItemReport()
        {
            string report = ItemReaderText + "\n" + "Hex: " + HexString + "\n\n";

            report += "Type: " + Enum.GetName(typeof(ItemType), Type) + "\n";

            report += "\n";

            if (HP != 0)
            {
                report += "HP: " + HP.ToString() + "\n";
            }
            if (TP != 0)
            {
                report += "TP: " + TP.ToString() + "\n";
            }
            if (ATP != 0)
            {
                report += "ATP: " + ATP.ToString() + "\n";
            }
            if (DFP != 0)
            {
                report += "DFP: " + DFP.ToString() + "\n";
            }
            if (MST != 0)
            {
                report += "MST: " + MST.ToString() + "\n";
            }
            if (ATA != 0)
            {
                report += "ATA: " + ATA.ToString() + "\n";
            }
            if (EVP != 0)
            {
                report += "EVP: " + EVP.ToString() + "\n";
            }
            if (LCK != 0)
            {
                report += "LCK: " + LCK.ToString() + "\n";
            }
            if (EFR != 0)
            {
                report += "EFR: " + EFR.ToString() + "\n";
            }
            if (EIC != 0)
            {
                report += "EIC: " + EIC.ToString() + "\n";
            }
            if (ETH != 0)
            {
                report += "ETH: " + ETH.ToString() + "\n";
            }
            if (ELT != 0)
            {
                report += "ELT: " + ELT.ToString() + "\n";
            }
            if (EDK != 0)
            {
                report += "EDK: " + EDK.ToString() + "\n";
            }

            report += "\n";

            report += "HUmar:     " + (((EquipMask & HUmarMask) > 0) ? "x" : "") + "\n";
            report += "HUnewearl: " + (((EquipMask & HUnewearlMask) > 0) ? "x" : "") + "\n";
            report += "HUcast:    " + (((EquipMask & HUcastMask) > 0) ? "x" : "") + "\n";
            report += "HUcaseal:  " + (((EquipMask & HUcasealMask) > 0) ? "x" : "") + "\n";
            report += "RAmar:     " + (((EquipMask & RAmarMask) > 0) ? "x" : "") + "\n";
            report += "RAmarl:    " + (((EquipMask & RAmarlMask) > 0) ? "x" : "") + "\n";
            report += "RAcast:    " + (((EquipMask & RAcastMask) > 0) ? "x" : "") + "\n";
            report += "RAcaseal:  " + (((EquipMask & RAcasealMask) > 0) ? "x" : "") + "\n";
            report += "FOmar:     " + (((EquipMask & FOmarMask) > 0) ? "x" : "") + "\n";
            report += "FOmarl:    " + (((EquipMask & FOmarlMask) > 0) ? "x" : "") + "\n";
            report += "FOnewm:    " + (((EquipMask & FOnewmMask) > 0) ? "x" : "") + "\n";
            report += "FOnewearl: " + (((EquipMask & FOnewearlMask) > 0) ? "x" : "") + "\n";

            return(report);
        }
Exemplo n.º 28
0
        public MST primGenerateMST()
        {   
            // populates list of distances
            List<primState> cost_table = new List<primState>();
            for (int i = 0; i < Cities.Length; i++)
            {
                for (int j = 0; j < Cities.Length; j++)
                {
                    primState state = new primState(Cities[i], Cities[j]);
                    if (i == j)
                    {
                        state.setCost(double.PositiveInfinity);
                    }
                    cost_table.Add(state);
                }
            }

            // sort list: O(n^2), worst case. Average case likely O(nlogn), assuming LINQ implements quicksort under-the-hood
            cost_table = cost_table.OrderBy(State => State.cost).ToList();

            // FIND MST
            // initialize mst to contain the smallest edge
            MST mst = new MST();
            Random random = new Random();
            //mst.root = new MSTNode(cost_table.ElementAt(0).startCity);
            int index = random.Next(0, cost_table.Count);
            mst.root = new MSTNode(cost_table.ElementAt(index).startCity);
            mst.root.addChild(new MSTNode(cost_table.ElementAt(index).endCity));
            MSTNode curNode = null;

            cost_table.RemoveAt(0);

            // create container of cities in the tree for convenience later on
            ArrayList citiesInMst = new ArrayList();
            citiesInMst.Add(mst.root.getCity());
            citiesInMst.Add(mst.root.getChildren().ElementAt(0).getCity()); // root only has one child

            while (citiesInMst.Count < Cities.Length) // grow mst one city at a time until it connects each city (until its size is Cities.length)
            {
                foreach (primState curEdge in cost_table) // iterate across remaining (unused) edges from shortest to longest
                {
                    curNode = mst.findNode(curEdge.startCity);
                    if (curNode != null) // if the start of current edge is already in the tree (expand the current tree, no parallel tree growth for this algorithm)...
                    {
                        // only if the end of current edge is NOT in the tree (no cycles allowed)...
                        if(!citiesInMst.Contains(curEdge.endCity))
                        {
                            curNode.addChild(new MSTNode(curEdge.endCity));
                            citiesInMst.Add(curEdge.endCity);
                            cost_table.Remove(curEdge); // O(n) complexity
                            break;
                        }
                    }
                }
            }
            return mst;
        }
Exemplo n.º 29
0
    public static void Main()
    {
        MST ms = new MST();

        ms.TestMst();
    }
Exemplo n.º 30
0
        public ArrayList preorderTraversal(MST mst)
        {
            // initialize path with root of mst
            ArrayList path = new ArrayList();
            MSTNode curNode = mst.root;

            // recurse into tree
            path = preorderTraversalRecursive(curNode, path);

            return path;
        }
Exemplo n.º 31
0
        /// <summary>
        /// Prints the item report
        /// </summary>
        /// <returns>The item report</returns>
        public override string ItemReport()
        {
            string report = ItemReaderText + "\n" + "Hex: " + HexString + "\n\n";

            report += "Type: " + Enum.GetName(typeof(ItemType), Type) + "\n";

            if (RequirementLevel != 0)
            {
                report += "Requirement: Level " + RequirementLevel + " \n";
            }

            if (Type == ItemType.Frame)
            {
                report += "Slots: " + Slots.ToString() + "\n";
            }

            report += "Base DFP: " + DFP.ToString() + "\n";
            report += "Base EVP: " + EVP.ToString() + "\n";

            report += "DFP Roll: " + VariableDFP.ToString() + "/" + (MaxDFP - DFP).ToString() + "\n";
            report += "EVP Roll: " + VariableEVP.ToString() + "/" + (MaxEVP - EVP).ToString() + "\n";

            report += "\n";

            if (HP != 0)
            {
                report += "HP: " + HP.ToString() + "\n";
            }
            if (TP != 0)
            {
                report += "TP: " + TP.ToString() + "\n";
            }
            if (ATP != 0)
            {
                report += "ATP: " + ATP.ToString() + "\n";
            }
            if (MST != 0)
            {
                report += "MST: " + MST.ToString() + "\n";
            }
            if (ATA != 0)
            {
                report += "ATA: " + ATA.ToString() + "\n";
            }
            if (LCK != 0)
            {
                report += "LCK: " + LCK.ToString() + "\n";
            }
            if (EFR != 0)
            {
                report += "EFR: " + EFR.ToString() + "\n";
            }
            if (EIC != 0)
            {
                report += "EIC: " + EIC.ToString() + "\n";
            }
            if (ETH != 0)
            {
                report += "ETH: " + ETH.ToString() + "\n";
            }
            if (ELT != 0)
            {
                report += "ELT: " + ELT.ToString() + "\n";
            }
            if (EDK != 0)
            {
                report += "EDK: " + EDK.ToString() + "\n";
            }

            report += "\n";

            report += "HUmar:     " + (((EquipMask & HUmarMask) > 0) ? "x" : "") + "\n";
            report += "HUnewearl: " + (((EquipMask & HUnewearlMask) > 0) ? "x" : "") + "\n";
            report += "HUcast:    " + (((EquipMask & HUcastMask) > 0) ? "x" : "") + "\n";
            report += "HUcaseal:  " + (((EquipMask & HUcasealMask) > 0) ? "x" : "") + "\n";
            report += "RAmar:     " + (((EquipMask & RAmarMask) > 0) ? "x" : "") + "\n";
            report += "RAmarl:    " + (((EquipMask & RAmarlMask) > 0) ? "x" : "") + "\n";
            report += "RAcast:    " + (((EquipMask & RAcastMask) > 0) ? "x" : "") + "\n";
            report += "RAcaseal:  " + (((EquipMask & RAcasealMask) > 0) ? "x" : "") + "\n";
            report += "FOmar:     " + (((EquipMask & FOmarMask) > 0) ? "x" : "") + "\n";
            report += "FOmarl:    " + (((EquipMask & FOmarlMask) > 0) ? "x" : "") + "\n";
            report += "FOnewm:    " + (((EquipMask & FOnewmMask) > 0) ? "x" : "") + "\n";
            report += "FOnewearl: " + (((EquipMask & FOnewearlMask) > 0) ? "x" : "") + "\n";

            return(report);
        }
        public void NotContainsEdgeTest()
        {
            var mst = MST.MinimumSpanningTree(m_graph);

            Assert.False(mst.ContainsEdge(m_level1pos[1], m_level1pos[2]));
        }