多维数组概率 [英] multidimensional array probability

查看:88
本文介绍了多维数组概率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早上好,我已经有一段时间在研究这个问题了,似乎无法分析如何使用PHP或javascript输出数组概率,如果有人设法解决这个问题,请提前感谢

Good day, I have been playing with this problem for some time now, and can't seem to analyze how to output the array probabilities, using PHP or javascript, had anyone manage to solve this problem, thanks in advance

示例:

$arrayNms = [
    ["A", "B", "C"],
    ["Q", "P"],
    ["CC", "C3"]
];


/*
OUTPUT
A, Q, CC
A, Q, C3
A, P, CC
A, P, C3
B, Q, CC
B, Q, C3
B, P, CC
B, P, C3
C, Q, CC
C, Q, C3
C, P, CC
C, P, C3
*/

//this is what I got so far, but can't seem to output the desired values
    $arr1 = [];
    for ($i = count($arrayNms) - 1; $i >= 0; $i--) {
        for ($j=0; $j < count($arrayNms[$i]); $j++) { 
            $prdName1 = $arrayNms[$i][$j];
            if(array_key_exists(($i+1), $arrayNms)){
                for ($k=0; $k < count($arrayNms[$i+1]); $k++) { 
                    $prdName2 = $arrayNms[$i][$k];
                    print_r($prdName2.', '.$prdName1);
                }
            }
        }
    }

谢谢

推荐答案

这似乎是大多数教科书给学生学习递归函数的一种挑战。这样的事情将提供所需的输出,并且不管 $ arrayNms (只要至少有一个)中有多少个值数组都可以工作:

This looks like the kind of challenge most textbooks give students to learn about recursive functions. Something like this would provide the desired output, and will work no matter how many arrays of values are in $arrayNms (as long as there is at least one):

function print_values($array, $index = 0, $base = "") {
    // check if there's another array of values after this one
    $is_last = !isset($array[$index + 1]);

    // loop through all values in the given sub-array
    foreach ($array[$index] as $value) {
        if ($is_last) {
            // if this is the last array of values, output the current value
            echo $base . $value . PHP_EOL;
        } else {
            // otherwise, append this value to the base and process the next array
            print_values($array, $index + 1, $base . $value . ", ");
        }
    }
}

$arrayNms = [
    ["A", "B", "C"],
    ["Q", "P"],
    ["CC", "C3"]
];

print_values($arrayNms);

输出:

A, Q, CC
A, Q, C3
A, P, CC
A, P, C3
B, Q, CC
B, Q, C3
B, P, CC
B, P, C3
C, Q, CC
C, Q, C3
C, P, CC
C, P, C3

这篇关于多维数组概率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆