Last active
June 5, 2016 04:16
-
-
Save esase/78b5d9213dbe305972cb to your computer and use it in GitHub Desktop.
Union find [algorithm]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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