Skip to content

Commit

Permalink
Migrating the source files from splex
Browse files Browse the repository at this point in the history
  • Loading branch information
peekxc committed Aug 15, 2023
1 parent 074e2d9 commit 6f5fe25
Show file tree
Hide file tree
Showing 24 changed files with 7,225 additions and 49 deletions.
3 changes: 1 addition & 2 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
.PHONY : docs
docs :
rm -rf docs/build/
sphinx-autobuild -b html --watch simplextree/ docs/source/ docs/build/


.PHONY : run-checks
run-checks :
isort --check .
Expand Down
75 changes: 75 additions & 0 deletions include/UnionFind.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
//----------------------------------------------------------------------
// Disjoint-set data structure
// File: union_find.h
//----------------------------------------------------------------------
// Copyright (c) 2018 Matt Piekenbrock. All Rights Reserved.
//
// Class definition based off of data-structure described here:
// https://en.wikipedia.org/wiki/Disjoint-set_data_structure

#ifndef UNIONFIND_H_
#define UNIONFIND_H_

#include <cstddef> // size_t
#include <vector> // vector
#include <numeric> // iota
#include <algorithm> // transform

struct UnionFind {
using idx_t = std::size_t;
using idx_v = std::vector< size_t >;
idx_t size;
mutable idx_v parent, rank;

UnionFind(const idx_t _size) : size(_size), parent(_size), rank(_size){
std::iota(parent.begin(), parent.end(), 0);
}

// Main operations
void Union(const idx_t x, const idx_t y){
if (x >= size || y >= size){ return; }
const idx_t xRoot = Find(x), yRoot = Find(y);
if (xRoot == yRoot){ return; }
else if (rank[xRoot] > rank[yRoot]) { parent[yRoot] = xRoot; }
else if (rank[xRoot] < rank[yRoot]) { parent[xRoot] = yRoot; }
else if (rank[xRoot] == rank[yRoot]) {
parent[yRoot] = parent[xRoot];
rank[xRoot] = rank[xRoot] + 1;
}
}
idx_t Find(const idx_t x) const {
if (x >= size || parent[x] == x){ return x; }
else {
parent[x] = Find(parent[x]);
return parent[x];
}
}
void AddSets(const idx_t n_sets){
parent.resize(size + n_sets);
std::iota(parent.begin() + size, parent.end(), size); // parent initialized incrementally
rank.resize(size + n_sets, 0); // rank all 0
size += n_sets;
}

// Convenience functions
void UnionAll(const idx_v& idx){
if (idx.size() <= 1){ return; }
const idx_t n_pairs = idx.size()-1;
for (idx_t i = 0; i < n_pairs; ++i){ Union(idx[i], idx[i+1]); }
}
idx_v FindAll(const idx_v& idx){
if (idx.size() == 0){ return idx_v(); }
idx_v cc = idx_v(idx.size());
std::transform(idx.begin(), idx.end(), cc.begin(), [this](const size_t i){
return(Find(i));
});
return(cc);
}
idx_v ConnectedComponents(){
idx_v cc = idx_v(size);
for (size_t i = 0; i < size; ++i){ cc[i] = Find(i); }
return(cc);
}
}; // class UnionFind

#endif
Loading

0 comments on commit 6f5fe25

Please sign in to comment.