【问题标题】:Algorithm to determine all possibilities for names given an array [in PHP]?确定给定数组[在PHP中]名称的所有可能性的算法?
【发布时间】:2014-11-26 18:30:57
【问题描述】:

此处的代码与项目中的代码不匹配导致问题。

【问题讨论】:

  • 你的脚本永远不会结束,因为只有 10*10 种不同的方式来组合单词。
  • 假设您没有两次使用同一个词并且w1w2w2w1 不同,则有九十种组合。我不知道你从哪里得到 2^10
  • 如果您允许将单词与其自身组合,则为 10*10。如果您想要不同单词的组合,则为 10*9。如果两个单词的顺序无关紧要,就是10*9/2。

标签: php arrays algorithm


【解决方案1】:
foreach ($words as $first) {
    foreach ($words as $second) {
        $taken[] = $first.$second;
    }
}

【讨论】:

  • 只有324,不应该还有更多吗?
  • 这并不是所有的可能性。
  • 这成功了,我的帖子和实际脚本不匹配导致了混乱。谢谢。
【解决方案2】:

如果您希望所有可能的组合都没有重复(例如:w1w1),请使用:

$allCombinations = null;
$words = array('w1', 'w2', 'w3', 'w4', 'w5', 'w6', 'w7', 'w8', 'w9', 'w10');

foreach ($words as $word1)
{
    foreach ($words as $word2)
    {
        if ($word1 != $word2)
        {
            $allCombinations[] = $word1.$word2;
        }
    }
}

echo count ($allCombinations); // The count is 90, and that's what it should be.
print_r($allCombinations);

【讨论】:

  • 仍然没有给出所有的可能性(只有 305 个)。
  • 应该只有 100 种可能性 (10^2),减去我删除的重复项。你的方程式是错误的,你的 305 也是错误的,我不知道你从哪里得到的。
  • 见上面的评论。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 2012-06-16
  • 1970-01-01
  • 1970-01-01
  • 2015-05-01
  • 2015-10-07
相关资源
最近更新 更多