php – 具有超过3700万种可能性的多个foreach

前端之家收集整理的这篇文章主要介绍了php – 具有超过3700万种可能性的多个foreach前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的任务是使用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.

原文链接:https://www.f2er.com/php/130343.html

猜你在找的PHP相关文章