我懷疑這是正確的方法。會發生什么?您可以向方法提供任意數量的數組...[ 'jupiter', 'saturn',][ 'is', 'was',][ 'old', 'big', 'loved',]并創造...[ 'jupiter is big', 'jupiter is loved', 'jupiter is old', 'jupiter was big', 'jupiter was loved', 'jupiter was old', 'saturn is big', 'saturn is loved', 'saturn is old', 'saturn was big', 'saturn was loved', 'saturn was old',]你應該怎么做?Stackoverflow 喜歡嘗試,所以就開始吧 ??我的方法目前有兩個重復函數(帶有嵌套的 for 循環)和十幾個其他 for 循環,這不是您想象的實現此目的的最快方法。我確實第一次嘗試使用聰明的數學,但開始讓自己感到困惑。如果您有更好的解決方案,請您也解釋一下!
1 回答

四季花海
TA貢獻1811條經驗 獲得超5個贊
這是我的代碼,只有一個遞歸函數。它還接受一個矩陣作為參數,而不是 N 個數組。
function generateList($data){
if (count($data) == 0){
return null;
}
$current = $data[0];
$left = array_slice($data, 1);
$permutations = generateList($left);
$r = [];
foreach($current as $item){
if ($permutations){
foreach ($permutations as $rest) {
$r[] = $item . ' ' . $rest;
}
}
else {
$r[] = $item;
}
}
return $r;
}
$data = [
['jupiter', 'saturn'],
['is', 'was'],
['old', 'big', 'loved']
];
var_dump(generateList($data));
- 1 回答
- 0 關注
- 102 瀏覽
添加回答
舉報
0/150
提交
取消