Created
June 26, 2013 18:02
-
-
Save ackintosh/5869768 to your computer and use it in GitHub Desktop.
Permutation
This file contains hidden or 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 Permutation | |
{ | |
public static function instance() { return new self(); } | |
public function run(Array $nums, $depth, Array $path = array()) | |
{ | |
if (count($nums) < $depth) throw new Exception(); | |
if ($depth === 0) return array($path); | |
$ret = array(); | |
for ($i = 0; $i < count($nums); $i++) { | |
$minus_one = $this->minus_one($nums, $i); | |
$ret = array_merge($ret, $this->run($minus_one, $depth - 1, $this->plus_one($path, $nums[$i]))); | |
} | |
return $ret; | |
} | |
public function minus_one(Array $nums, $index) | |
{ | |
$ret = array(); | |
for ($i = 0; $i < count($nums); $i++) { | |
if ($i === $index) continue; | |
$ret[] = $nums[$i]; | |
} | |
return $ret; | |
} | |
public function plus_one(Array $path, $num) | |
{ | |
$path[] = $num; | |
return $path; | |
} | |
} | |
$result = Permutation::instance()->run(array(1, 2, 3, 4, 5), 3); | |
var_dump($result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment