Skip to content

Instantly share code, notes, and snippets.

@esase
Last active June 5, 2016 04:16
Show Gist options
  • Save esase/78b5d9213dbe305972cb to your computer and use it in GitHub Desktop.
Save esase/78b5d9213dbe305972cb to your computer and use it in GitHub Desktop.
Union find [algorithm]
<?php
class UnionFind
{
/**
* Elements
* @var array
*/
public $elements;
/**
* Add a new set
*
* @param $x
* @return void
*/
public function addSet($x)
{
$this->elements[$x] = $x;
}
/**
* Find
*
* @param integer $x
* @return integer
*/
public function find($x)
{
if ($this->elements[$x] == $x) {
return $x;
}
return $this->elements[$x] = $this->find($this->elements[$x]);
}
/**
* Union
*
* @param integer $x
* @param integer $y
* @return void
*/
public function union($x, $y)
{
$x = $this->find($x);
$y = $this->find($y);
if (rand(0, 1000) % 2 == 0) {
$this->elements[$x] = $y;
return;
}
$this->elements[$y] = $x;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment