前端jquery:
一.
function permutate(str) {
//儲存每一輪遞歸的排列結果
var result = [];
//初始條件:長度為1
if (str.length == 1) {
return [str]
} else {
//求剩餘子串的全排列,對每個排列進行周遊
var preResult = permutate(str.slice(1));
for (var j = 0; j < preResult.length; j++) {
for (var k = 0; k < preResult[j].length + 1; k++) {
//将首字母插入k位置
var temp = preResult[j].slice(0, k) + str[0] + preResult[j].slice(k);
if($.inArray(temp,result) > -1){ //判斷數組中重複元素
}else{
result.push(temp);
}
}
}
return result;
}
}
permutate('123'); 輸出的結果是:123,132,213,231,312,321.
二.
// 全排列組合
function getGroup(data, index = 0, group = []) {
var need_apply = new Array();
need_apply.push(data[index]);
for(var i = 0; i < group.length; i++) {
need_apply.push(group[i] + data[index]);
}
group.push.apply(group, need_apply);
if(index + 1 >= data.length) return group;
else return getGroup(data, index + 1, group);
}
var w = ['千','百','十','個'];
console.log(getGroup(w)); 輸出的結果是:如下圖
後端php:
1.
function arrangement($a, $m) {
$r = array();
$n = count($a);
if ($m <= 0 || $m > $n) {
return $r;
}
for ($i=0; $i<$n; $i++) {
$b = $a;
$t = array_splice($b, $i, 1);
if ($m == 1) {
$r[] = $t;
} else {
$c = arrangement($b, $m-1);
foreach ($c as $v) {
$r[] = array_merge($t, $v);
}
}
}
return $r;
}
// ====== 測試 ======
$a = array("a", "b", "c", "d","e");
$r = arrangement($a, 3);
foreach($r as $k=>$v){
$r[$k] = implode("",$v);
}
echo "<pre>";
print_r($r);exit;
2.
function combination($a, $m) {
$r = array();
$n = count($a);
if ($m <= 0 || $m > $n) {
return $r;
}
for ($i=0; $i<$n; $i++) {
$t = array($a[$i]);
if ($m == 1) {
$r[] = $t;
} else {
$b = array_slice($a, $i+1);
$c = combination($b, $m-1);
foreach ($c as $v) {
$r[] = array_merge($t, $v);
}
}
}
return $r;
}
// ====== 測試 ======
$a = array("a", "b", "c", "d","e");
$r = arrangement($a, 3);
foreach($r as $k=>$v){
$r[$k] = implode("",$v);
}
echo "<pre>";
print_r($r);exit;
3.
function getCombinationToString($arr,$m){
$result = array();
if($m == 1){
return $arr;
}
if($m == count($arr)){//當取出的個數等于數組的長度,就是隻有一種組合,即本身
$result[] = implode('',$arr);
return $result;
}
$temp_firstelement = $arr[0];
unset($arr[0]);
$arr = array_values($arr);
$temp_first1 = getCombinationToString($arr,$m - 1);
foreach($temp_first1 as $s){
$s = $temp_firstelement.$s;
$result[] = $s;
}
unset($temp_first1);
$temp_first2 = getCombinationToString($arr,$m);
foreach($temp_first2 as $s){
$result[] = $s;
}
unset($temp_first2);
return $result;
}
$arr = array("a","b","c","d","e");//1~6的數組
$result = getCombinationToString($arr,3);//6個數裡面,取出2個數有多少種組合(即不考慮順序)
$data['count'] = count($result);//組合種數
$data['data'] = $result;//各種資料組合
echo "<pre>";
print_r($data);exit;