public void ConnectedTest1()
 {
     var uf = new UnionFind<double>(EqualityComparer<double>.Default);
     uf.Union(3.14, 2.71);
     uf.Union(1, 2);
     uf.Union(3.14, 1.618);
     uf.Union(2.71, 0);
     Assert.Equal(false, uf.Connected(1, 3.14));
     Assert.Equal(true, uf.Connected(2.71, 1.618));
     Assert.Equal(true, uf.Connected(0, 1.618));
 }
        private static int FindNearestMapSection(IList <MapSection> mapSections, int mapSectionIndex, UnionFind unionFind)
        {
            MapSection start        = mapSections[mapSectionIndex];
            int        closestIndex = mapSectionIndex;
            int        distance     = Int32.MaxValue;

            for (int i = 0; i < mapSections.Count; i++)
            {
                if (i == mapSectionIndex)
                {
                    continue;
                }
                if (unionFind.Connected(i, mapSectionIndex))
                {
                    continue;
                }
                int distanceBetween = DistanceBetween(start, mapSections[i]);
                if (distanceBetween < distance)
                {
                    distance     = distanceBetween;
                    closestIndex = i;
                }
            }
            return(closestIndex);
        }
        public KruskalMST(WeightedUnDirectedGraph g)
        {
            this.G           = g;
            this.MSTEdges    = new Queue <WeightedUndirectedEdge>();
            this.TotalWeight = 0;

            minHeap = new MinHeap <WeightedUndirectedEdge>(this.G.GetVertices() * this.G.GetVertices());
            Uf      = new UnionFind(G.GetVertices());

            foreach (var vertex in G.GetVerticesList())
            {
                foreach (var edge in G.GetAdjacentEdges(vertex))
                {
                    minHeap.Insert(edge);
                }
            }

            while (!minHeap.IsEmpty())
            {
                WeightedUndirectedEdge edge = minHeap.ExtractMin();
                int u = edge.Either();
                int v = edge.Other(u);

                if (!Uf.Connected(u, v))
                {
                    MSTEdges.Enqueue(edge);
                    TotalWeight += edge.Weight();
                    Uf.Union(u, v);
                }
            }
        }
Beispiel #4
0
        public void Connected_WhenEachSetHasOnly1Component_WillBeFalse()
        {
            UnionFind unionFind = new UnionFind(3);

            bool isConnected = unionFind.Connected(1, 2);

            Assert.IsFalse(isConnected);
        }
Beispiel #5
0
        public void Connected_WhenUnionIsCalledOnComponents_WillBeTrue()
        {
            UnionFind unionFind = new UnionFind(3);

            unionFind.Union(1, 2);

            bool isConnected = unionFind.Connected(1, 2);

            Assert.IsTrue(isConnected);
        }
Beispiel #6
0
        /// <summary>
        /// Reassembles fragmented IP packets and hands them up to the transport
        /// layer once they have been fully reassembled.
        /// </summary>
        /// <param name="packet">An IP packet representing a fragment of a
        /// fragmented packet.</param>
        public void ReassemblePacket(IpPacket packet)
        {
            // Fragments belong to the same datagram if they have the same source,
            // destination, protocol, and identifier fields (RFC 791, p. 28).
            var hash = Hash.Sha256(packet.Source +
                                   packet.Destination.ToString() + packet.Protocol +
                                   packet.Identification
                                   );

            // Group related fragments in a set under the same dictionary key.
            if (!fragments.ContainsKey(hash))
            {
                fragments.Add(hash, new HashSet <IpPacket>());
            }
            fragments[hash].Add(packet);
            // Figure out if we already have all fragments so that we can reassemble
            // the original packet.
            var uf = new UnionFind(65536);
            var originalDataSize = 0;

            foreach (var p in fragments[hash])
            {
                var from = p.FragmentOffset * 8;
                var to   = from + p.Data.Length - 1;
                uf.Union(from, to);
                uf.Union(to, to + 1);
                // Derive original packet size from last fragment.
                if (!p.Flags.HasFlag(IpFlag.MoreFragments))
                {
                    originalDataSize = from + p.Data.Length;
                }
            }
            // If this is still 0, last segment has not arrived yet.
            if (originalDataSize == 0)
            {
                return;
            }
            // If the first and the last byte are not part of the same component,
            // not all fragments have arrived yet.
            if (!uf.Connected(0, originalDataSize))
            {
                return;
            }
            var data = new byte[originalDataSize];

            foreach (var p in fragments[hash])
            {
                Array.Copy(p.Data, 0, data, p.FragmentOffset * 8, p.Data.Length);
            }
            // Hand up reassembled data to transport layer.
            HandUp(data, packet.Protocol);
        }
Beispiel #7
0
        public void TestConnected(Parameters <IndexPair, bool> parameters)
        {
            var unionFind = new UnionFind(parameters.InitialSize);

            foreach (var pair in parameters.PairsToMerge)
            {
                unionFind.Unify(pair.FirstIndex, pair.SecondIndex);
            }

            foreach (var inputOutput in parameters.InputOutput)
            {
                Assert.That(unionFind.Connected(inputOutput.Input.FirstIndex, inputOutput.Input.SecondIndex), Is.EqualTo(inputOutput.ExpectedOutput));
            }
        }
Beispiel #8
0
    public KruskaMST(EdgeWeightedGraph g)
    {
        m_mst = new Queue <Edge>();
        MinPQ <Edge> pq = new MinPQ <Edge>(g.Edges());
        UnionFind    uf = new UnionFind(g.V());

        while (!pq.IsEmpty() && m_mst.Count < g.V() - 1)
        {
            Edge e = pq.DeleteTop();
            int  v = e.Either();
            int  w = e.Other(v);
            if (uf.Connected(v, w))
            {
                continue;
            }
            uf.Union(v, w);
            m_mst.Enqueue(e);
        }
    }
Beispiel #9
0
        public void Test01()
        {
            UnionFind uf = new UnionFind(10);

            int[] pArr = { 4, 3, 6, 9, 2, 5, 7, 6 };
            int[] qArr = { 3, 8, 5, 4, 1, 0, 2, 1 };
            for (int i = 0; i < pArr.Length; i++)
            {
                int p = pArr[i], q = qArr[i];
                if (uf.Connected(p, q))
                {
                    continue;
                }

                uf.Union(p, q);
                Console.WriteLine($"{p} {q}");
            }

            Console.WriteLine(uf.Count + " Components");
        }
    public bool[] FriendRequests(int n, int[][] restrictions, int[][] requests)
    {
        bool[] res = new bool[requests.GetLength(0)];

        var uf = new UnionFind(n);

        for (int i = 0; i < requests.GetLength(0); i++)
        {
            int[] req = requests[i];

            bool valid = true;
            if (!uf.Connected(req[0], req[1]))
            {
                int u = uf.Find(req[0]), v = uf.Find(req[1]);

                for (int k = 0; k < restrictions.GetLength(0); k++)
                {
                    int[] restr = restrictions[k];

                    int x = uf.Find(restr[0]), y = uf.Find(restr[1]);

                    if ((u == x && v == y) || (u == y && v == x))
                    {
                        valid = false;
                        break;
                    }
                }
            }

            if (valid)
            {
                uf.Union(req[0], req[1]);
                res[i] = true;
            }
        }

        return(res);
    }
Beispiel #11
0
 public void GivenInputExceedsLimit_WhenConnected_ThenThrowNumberExceedsLimitException()
 {
     Assert.Throws <UnionFind.NumberExceedsLimitException>(() => qf.Connected(11, 0));
     Assert.Throws <UnionFind.NumberExceedsLimitException>(() => qf.Connected(0, 11));
 }