Skip to content

Instantly share code, notes, and snippets.

@ackintosh
Created June 26, 2013 18:02
Show Gist options
  • Save ackintosh/5869768 to your computer and use it in GitHub Desktop.
Save ackintosh/5869768 to your computer and use it in GitHub Desktop.
Permutation
<?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