배열 조합의 함수를 궁리하다

1623 단어 function
<?php
function getSequenceAry($arr)
{
	if (count($arr) == 1) {
		return array($arr);
	}
	$arrRet = array();
	foreach ($arr as $k => $v) {
		$arr2 = $arr;
		unset($arr2[$k]);
		$arrOrderList = getSequenceAry($arr2);
		foreach ($arrOrderList as $order) {
			array_unshift($order, $v);
			$arrRet[] = $order;
		}
	}
	return $arrRet;
}

function getSequenceStr($arr)
{
	if (count($arr) == 1) {
		return $arr;
	}
	$arrRet = array();
	foreach ($arr as $k => $v) {
		$arr2 = $arr;
		unset($arr2[$k]);
		$arrOrderList = getSequenceStr($arr2);
		foreach ($arrOrderList as $order) {
			$arrRet[] = $v . $order;
		}
	}
	return $arrRet;
}


print_r(getSequenceAry(array(1,2,3)));
print_r(getSequenceStr(array(1,2,3)));

------------------------ output ------------------------


Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [1] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 2
        )

    [2] => Array
        (
            [0] => 2
            [1] => 1
            [2] => 3
        )

    [3] => Array
        (
            [0] => 2
            [1] => 3
            [2] => 1
        )

    [4] => Array
        (
            [0] => 3
            [1] => 1
            [2] => 2
        )

    [5] => Array
        (
            [0] => 3
            [1] => 2
            [2] => 1
        )

)
Array
(
    [0] => 123
    [1] => 132
    [2] => 213
    [3] => 231
    [4] => 312
    [5] => 321
)

좋은 웹페이지 즐겨찾기