我的任务是使用8个块的数据来创建所有可能性的列表。

8个块具有以下几种可能性:

*Block 1: 12 possibilities
*Block 2: 8 possibilities
*Block 3: 8 possibilities
*Block 4: 11 possibilities
*Block 5: 16 possibilities
*Block 6: 11 possibilities
*Block 7: 5 possibilities
*Block 8: 5 possibilities

这给出了37,171,200的潜在可能性。

我试着简单地做,并且只限于显示以正确的字符串长度返回的值,如下所示:
foreach($block1 AS $b1){
    foreach($block2 AS $b2){
        foreach($block3 AS $b3){
            foreach($block4 AS $b4){
                foreach($block5 AS $b5){
                    foreach($block6 AS $b6){
                        foreach($block7 AS $b7){
                            foreach($block8 AS $b8){
                                if (strlen($b1.$b2.$b3.$b4.$b5.$b6.$b7.$b8) == 16)
                                {
                                    echo $b1.$b2.$b3.$b4.$b5.$b6.$b7.$b8.'<br/>';
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

但是,执行时间太长,无法计算。我想知道是否有人知道更简单的方法?

最佳答案

您可以通过缓存字符串前缀并记住它们的长度来改进算法。然后,您不必为每种组合都这样做。

$len = 16:

// array for remaining characters per level
$r = array($len);
// array of level parts
$p = array();
foreach ($block1 AS &$b1) {
    // skip if already too long
    if (($r[0] - strlen($b1)) <= 0) continue;
    $r[1] = $r[0] - strlen($b1);
    foreach ($block2 AS &$b2) {
        if (($r[1] - strlen($b2)) <= 0) continue;
        $r[2] = $r[1] - strlen($b2);
        foreach ($block3 AS $b3) {
            // …
            foreach ($block8 AS &$b8) {
                $r[8] = $r[7] - strlen($b8);
                if ($r[8] == 0) {
                    echo implode('', $p).'<br/>';
                }
            }
        }
    }
}

此外,在foreach中使用引用将在内部使用数组副本停止PHP。

关于php - 超过3700万种可能性的多重搜索,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9310621/

10-11 05:08