Math_Permutation.class.php
<?php
class Math_Permutation
{
private $max;
private $arrayRange = array();
private $arrayResult = array();
private $arrayResult2dim = array();
private $arrayResult2dimExpand = array();
public function __construct($max)
{
$this->set_max($max);
}
public function set_max($max)
{
$this->max = $max + 1;
$this->arrayRange = array();
$this->arrayResult = array();
$this->arrayRange = range(0, $max);
$this->arrayResult2dim = array();
$this->arrayResult2dimExpand = array();
}
public function get_arrayResult()
{
return $this->arrayResult;
}
public function get_arrayResult2dim()
{
if( 1 > count($this->arrayResult2dim) )
{
$this->convertArray_1to2();
}
return $this->arrayResult2dim;
}
public function get_arrayResult2dimExpand($array)
{
$keyY;
$keyX;
$line;
$value;
if( 1 > count($this->arrayResult2dim) )
{
$this->convertArray_1to2();
}
if( 1 > count($this->arrayResult2dimExpand) )
{
foreach($this->arrayResult2dim as $keyY => $line)
{
foreach($line as $keyX => $value)
{
$line[$keyX] = $array[$value];
}
$this->arrayResult2dimExpand[$keyY] = $line;
}
}
return $this->arrayResult2dimExpand;
}
public function generate($max = null, $str = '')
{
if( is_null($max) ) $max = $this->max;
$cnt;
$array = array();
if($max == 0)
{
$this->arrayResult[] = rtrim($str, ',');
return;
}
for($y = 0, $cnt = count($this->arrayRange); $y < $cnt; $y++)
{
$array = array_splice($this->arrayRange, $y, 1);
$this->generate($max - 1, $str . $array[0] . ',');
array_splice($this->arrayRange, $y, 0, $array);
}
}
private function convertArray_1to2()
{
$key;
$value;
foreach($this->arrayResult as $key => $value)
{
$this->arrayResult2dim[$key] = explode(',', $value);
}
}
}
呼び出し
<?php
require_once('Math_Permutation.class.php');
$array = array('a', 'b', 'c');
$o_permutation = new Math_Permutation(2);
$o_permutation->generate();
print "<pre>";
print_r( $o_permutation->get_arrayResult() );
print_r( $o_permutation->get_arrayResult2dim() );
print_r( $o_permutation->get_arrayResult2dimExpand($array) );
print "</pre>";
実行結果1
Array
(
[0] => 0,1,2
[1] => 0,2,1
[2] => 1,0,2
[3] => 1,2,0
[4] => 2,0,1
[5] => 2,1,0
)
実行結果2
Array
(
[0] => Array
(
[0] => 0
[1] => 1
[2] => 2
)
[1] => Array
(
[0] => 0
[1] => 2
[2] => 1
)
[2] => Array
(
[0] => 1
[1] => 0
[2] => 2
)
[3] => Array
(
[0] => 1
[1] => 2
[2] => 0
)
[4] => Array
(
[0] => 2
[1] => 0
[2] => 1
)
[5] => Array
(
[0] => 2
[1] => 1
[2] => 0
)
)
実行結果3
Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
)
[1] => Array
(
[0] => a
[1] => c
[2] => b
)
[2] => Array
(
[0] => b
[1] => a
[2] => c
)
[3] => Array
(
[0] => b
[1] => c
[2] => a
)
[4] => Array
(
[0] => c
[1] => a
[2] => b
)
[5] => Array
(
[0] => c
[1] => b
[2] => a
)
)