我正在用PHP编写一个应用程序,用户可以输入两组信息,并打印出两组的各种可能组合。目标是通过练习不同的问答模式,将其用作学习语言的教学工具。
例如,我们可能会练习“你有没有试过......?”的问题。加上四项活动中的一项,如蹦极,帆船,跳伞和水肺潜水。还有四种可能的答案:
用户将输入两组数据,然后应用程序将打印包含所有可能的问题和答案组合的卡片。例如,卡1看起来像这样:
下一张卡片可能如下所示:
正如您所看到的,有许多不同的可能组合。我们的想法是两个列表的长度相同,以便打印出所有可能性。同样重要的是,在任何卡上不得多次使用任何问题或答案,并且两张卡可以相同。最好的方法是什么?实际的输入和输出不是问题 - 我以前做过类似的事情。我只需要算法来生成组合。
编辑:我想我真正想要的是保持每张卡的活动顺序相同,但要有各种可能的答案组合。所以我真正需要的是能够生成以下索引集,以便从answers数组中获取数据。所以我真的想要更像这样的东西:......依此类推,直到产生了所有可能的组合。
答案 0 :(得分:5)
试试这个:
$activities = array(); // Input all your activities as elements here.
$responses = array(); // Input all your responses as elements here.
foreach ($activities as $activity) {
foreach ($responses as $response) {
echo $activities.' '.$response."\n";
}
}
答案 1 :(得分:1)
好的,按照新的标准,我想我明白了一点。
尝试递归。我的解决方案很乱,但我可以引导你完成它:
$activities = array('a', 'b', 'c', 'd'); // Input all your activities as elements here.
$responses = array(1, 2, 3, 4); // Input all your responses as elements here.
// Recursive function outputCombos accepts both arrays (for eventual output).
// $workingArray is the array of the current branch we're working with.
function outputCombos ($activities, $responses, $workingArray) {
// Once the working array has been loaded to the maximum amt, print everything out.
if (count($workingArray) == count($responses)) {
echo "Combo\n";
for ($x = 0; $x < count($activities); $x++) {
echo $activities[$x].'::'.$workingArray[$x]."\n";
}
// If the working array isn't full, add an element that isn't currently in the working array, and recursively run the function again.
} else {
foreach ($responses as $response) {
// Iterate through list of all possible responses, add it into a new working array and run the function if the response hasn't been used in this working array.
if (!in_array($response, $workingArray)) {
$newArray = $workingArray;
$newArray[] = $response;
outputCombos($activities, $responses, $newArray);
}
}
}
}
foreach ($responses as $response) {
echo '<pre>';
// Start each branch of tree with unique response (should be 4 in this case).
outputCombos($activities, $responses, array($response));
echo '</pre>';
}