/// <summary> /// Perform a Quick Find on a small text file. /// </summary> /// <param name="unionFind">The union find to be tested.</param> internal static void CommonUnionFindTiny(IUnionFind unionFind) { using (In input = new In("Algs4-Data\\TinyUF.txt")) { int initialComponentCount = input.ReadInt(); unionFind.IsolateComponents(initialComponentCount); while (!input.IsEmpty()) { int siteP = input.ReadInt(); int siteQ = input.ReadInt(); if (unionFind.Connected(siteP, siteQ)) { continue; } unionFind.Union(siteP, siteQ); } } Assert.AreEqual(2, unionFind.Count); }
static double UnionFindTest(IUnionFind uf, int n) { Stopwatch sw = new Stopwatch(); sw.Start(); Random rand = new Random(); // 进行n次操作, 每次随机选择两个元素进行合并 for (int i = 0; i < n; i++) { int a = rand.Next(n); int b = rand.Next(n); uf.UnitElement(a, b); } // 进行n次操作, 每次随机判断两个元素是否相连接 for (int i = 0; i < n; i++) { int a = rand.Next(n); int b = rand.Next(n); uf.IsConnected(a, b); } sw.Stop(); return(sw.Elapsed.TotalSeconds); }
/// <summary> /// Common portion of file input UnionFind tests. /// </summary> /// <param name="streamName">The name for the input stream.</param> /// <param name="unionFind">The union find to be tested.</param> /// <returns>The Union Find structure.</returns> public static IUnionFind UnionFindCommon(string streamName, IUnionFind unionFind) { if (null == streamName) { throw new ArgumentNullException("streamName"); } if (null == unionFind) { throw new ArgumentNullException("unionFind"); } using (In input = new In(streamName)) { int initialComponentCount = input.ReadInt(); unionFind.IsolateComponents(initialComponentCount); while (!input.IsEmpty()) { int siteP = input.ReadInt(); int siteQ = input.ReadInt(); if (unionFind.Connected(siteP, siteQ)) { continue; } unionFind.Union(siteP, siteQ); } return unionFind; } }
public void SetUp() { unionFind = UnionFind.Create(type, 5); unionFind.Connect(0, 1); unionFind.Connect(1, 3); unionFind.Connect(2, 4); }
public void MergeWith(IUnionFind <IData> tree) { if (Root != this) { Root.MergeWith(tree.Root); } else { MergeWithRoot(tree.Root); } }
private void MergeWithRoot(IUnionFind <IData> root) { if (Depth < root.Depth) { Root = root; } else if (Depth > root.Depth) { root.MergeWith(this); } else if (root != this) { Depth += 1; root.MergeWith(this); } }
private void TestFind(IUnionFind uf) { Assert.AreEqual(100, uf.Components().Count, "The given UnionFind algorithm must be defined for 100 nodes"); bool result; /* Initially, I find no path */ result = uf.Find(0, 1); Assert.AreEqual(result, false); /* Test directly connected nodes */ uf.Union(0, 1); result = uf.Find(0, 1); Assert.AreEqual(result, true); /* Test indirectly connected nodes */ uf.Union(1, 2); result = uf.Find(0, 2); Assert.AreEqual(result, true); /* Test non-connected nodes */ result = uf.Find(0, 9); Assert.AreEqual(result, false); /* Test find in an union of all nodes */ Random random = new Random(); List <int> components = uf.Components(); for (int i = 3; i < components.Count; i++) { uf.Union(i - 1, i); } components = uf.Components(); for (int i = 0; i < components.Count; i++) { int p = random.Next(0, components.Count); int q = random.Next(0, components.Count); result = uf.Find(p, q); Assert.AreEqual(result, true); } Assert.AreEqual(CountConnectedComponents(components), 1); }
private bool IsPercolated(IUnionFind uf, out int selected_top_cell, out int selected_bottom_cell) { selected_top_cell = -1; selected_bottom_cell = -1; foreach (var top_cell in top) { foreach (var bottom_cell in bottom) { if (!uf.IsConnected(top_cell, bottom_cell)) { continue; } selected_top_cell = top_cell; selected_bottom_cell = bottom_cell; return(true); } } return(false); }
/// <summary> /// Uses the given union find object to run the commands. /// </summary> /// <param name="algo"></param> /// <param name="commands"></param> public static void Run(IUnionFind algo, int[,] commands) { int x, y; for (int i = 0; i < commands.GetLength(0); i++) { x = commands[i, 0]; y = commands[i, 1]; if (algo.CheckIfConnected(x, y) == false) { Console.WriteLine("CHECK:\t{0} and {1} are not connected.", x, y); algo.CreateUnion(x, y); Console.WriteLine("UNION:\t{0} and {1} where successfully connected.", x, y); } else { Console.WriteLine("CHECK:\t{0} and {1} are already connected.", x, y); } } }
private void TestUnion(IUnionFind uf) { Assert.AreEqual(100, uf.Components().Count, "The given UnionFind algorithm must be defined for 100 nodes"); List <int> components; /* Test union of two nodes */ uf.Union(0, 1); components = uf.Components(); Assert.AreEqual(components[0], components[1]); Assert.AreEqual(CountConnectedComponents(components), components.Count - 1); /* Test union of three nodes */ uf.Union(1, 2); components = uf.Components(); Assert.AreEqual(components[0], components[1]); Assert.AreEqual(components[1], components[2]); Assert.AreEqual(CountConnectedComponents(components), components.Count - 2); /* Test random unions */ Random random = new Random(); List <Tuple <int, int> > connections = new List <Tuple <int, int> >(); for (int i = 0; i < components.Count; i++) { int p = random.Next(0, components.Count); int q = random.Next(0, components.Count); connections.Add(new Tuple <int, int>(p, q)); uf.Union(p, q); } components = uf.Components(); foreach (var con in connections) { Assert.AreEqual(components[con.Item1], components[con.Item2]); } }
public void Setup() { sut = new QuickFindUF(10); }
public void QuickUnionWeightedTests() { _unionFind = new UnionFindQuickUnionWeightedSize(Size); Assert.AreEqual(ExpectedString, GetNotConnectedUnions()); Assert.AreEqual(ExpectedCount, _unionFind.Count()); }
public void SetUp() { this.unionFind = new UnionFind<string>(); this.itemA = "a"; this.itemB = "b"; }
/// <summary> /// Algoritmo de Kruskal com diversas implementações. /// </summary> /// <param name="implementationType">Tipo de implemantação que será usada para executar o algoritmo</param> /// <returns></returns> public int Kruskal(KruskalType implementationType) { //Declaração de variáveis auxiliares int minimumSpaningTreeCost = 0; //IUnionFind é uma interface, sua implementação será escolhida no swich abaixo IUnionFind unionFind = null; //Verifica qual é o tipo de implementação do kruskal foi escolhida e executa as ações condizentes switch (implementationType) { case KruskalType.LinkedListUFHeapSort: //Union Find implementado com listas encadeadas unionFind = new UnionFindLL(this.numberOfVertices); //Faz o sorting com o HeapSort (in place) Sorting.Heap <Edge> .HeapSort(ref graphEdges); break; case KruskalType.TreeUFHeapSort: //Union Find implementado com arvores unionFind = new UnionFindT(this.numberOfVertices); //Faz o sorting com o HeapSort (in place) Sorting.Heap <Edge> .HeapSort(ref graphEdges); break; case KruskalType.LinkedListUFCountingSort: //Union Find implementado com listas encadeadas unionFind = new UnionFindLL(this.numberOfVertices); //Faz o sorting com o CountingSort graphEdges = Sorting.Sorting <Edge> .CountingSort(graphEdges, this.maxWeight); break; case KruskalType.TreeUFCountingSort: //Union Find implementado com arvores unionFind = new UnionFindT(this.numberOfVertices); //Faz o sorting com o CountingSort graphEdges = Sorting.Sorting <Edge> .CountingSort(graphEdges, this.maxWeight); break; default: throw new ArgumentException("Tipo de Kruskal não especificado."); } //Percorre a lista ordenada de Arestas. //Termina o looping quando todos os vértices já tiverem sido colocados na arvore geradora mínima. int i = 1; int j = 0; while (i < this.numberOfVertices) { //Decobre os conjuntos aos quais os vértices pertencem int set1 = unionFind.Find(graphEdges[j].Item2.vertexTo); int set2 = unionFind.Find(graphEdges[j].Item2.vertexFrom); //Verifica se os vértices pertencem ao mesmo grupo (forma ciclo) if (set1 != set2) { //Soma o risco da aresta ao risco total da arvore geradora mínima minimumSpaningTreeCost += graphEdges[j].Item1; //Une os conjuntos nos quais estão os vértices da aresta que foi adicionada na árvore geradora mínima unionFind.Union(set1, set2); i++; } j++; } return(minimumSpaningTreeCost); }
public QuickUnionWeighted(int vertices) { _unionFind = new UnionFind(vertices, new QuickUnionWeightedAlgorithm(vertices)); }
public void Setup() { _sut = new QuickUnionImprovementsUF(_count); }
public void Teardown() { _sut = null; }
public QuickFind(int vertices) { _unionFind = new UnionFind(vertices, new QuickFindAlgorithm()); }