unionfind

package module
v0.0.0-...-2bf90fd Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 12, 2020 License: MIT Imports: 1 Imported by: 2

README

unionfind

An idiomatic implementation of a weighted Union Find data structure with path compression in go.

Install

$ go get github.com/theodesp/unionfind

Usage

// Initialize with size
uf := unionfind.New(10)

// Union a,b connects components at index a and b
uf.Union(1, 2)
uf.Union(2, 3)
uf.Union(5, 6)
uf.Union(4, 6)

fmt.PrintLn(uf.Find(2)) // Prints 1
fmt.PrintLn(uf.Connected(1, 2)) // Prints true
fmt.PrintLn(uf.Connected(1, 3)) // Prints false

API

uf := unionfind.New(N)

Create a new Union Find Structure with size N.

uf.Union(p, q)

Connects p and q components.

uf.Find(p)

Attempts to find the Root component of p. Returns -1 if p is out of bounds.

uf.Root(p, q)

Same as Find.

uf.Connected(p, q)

Checks if p and q are connected.

EXTRA

There is also a goroutine safe version of unionfind in the file safe-unionfind.

Licence

MIT - Theo Despoudis

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ThreadSafeUnionFind

type ThreadSafeUnionFind struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func NewThreadSafeUnionFind

func NewThreadSafeUnionFind(size int) ThreadSafeUnionFind

func (*ThreadSafeUnionFind) Connected

func (suf *ThreadSafeUnionFind) Connected(p int, q int) bool

Unfortunately all the calls are coerced to writes thats why we use a Writer lock

func (*ThreadSafeUnionFind) Find

func (suf *ThreadSafeUnionFind) Find(p int) int

Root or Find

func (*ThreadSafeUnionFind) Root

func (suf *ThreadSafeUnionFind) Root(p int) int

func (*ThreadSafeUnionFind) Union

func (suf *ThreadSafeUnionFind) Union(p int, q int)

type UnionFind

type UnionFind struct {
	// contains filtered or unexported fields
}

func New

func New(size int) *UnionFind

New returns an initialized list of size

func (*UnionFind) Connected

func (uf *UnionFind) Connected(p int, q int) bool

Check if items p,q are connected

func (*UnionFind) Find

func (uf *UnionFind) Find(p int) int

Root or Find

func (*UnionFind) Root

func (uf *UnionFind) Root(p int) int

Root or Find traverses each parent element while compressing the levels to find the root element of p If we attempt to access an element outside the array it returns -1

func (*UnionFind) Union

func (uf *UnionFind) Union(p int, q int)

Union connects p and q by finding their roots and comparing their respective size arrays to keep the tree flat

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL