活到老学到老  

记录遇到问题的点点滴滴。

SKU组合算法 正序

7年前发布  · 1317 次阅读

PHP

<?php

function f(&$r, $t, $a, $depth, $end)
{
    if ($depth == $end) {
        if (count($t)) {
            $r[] = $t;
        }
    } else {
        $count = count($a[$depth]);
        for ($i = 0; $i < $count; $i++) {
            f($r, array_merge($t, [$a[$depth][$i]]), $a, $depth + 1, $end);
        }
    }
}

function combine($arr)
{
    $r = [];
    f($r, [], $arr, 0, count($arr));
    return $r;
}

$arr = [
    [1, 2],
    [3, 4],
];
print_r(combine($arr));
// preview
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 3
        )

    [1] => Array
        (
            [0] => 1
            [1] => 4
        )

    [2] => Array
        (
            [0] => 2
            [1] => 3
        )

    [3] => Array
        (
            [0] => 2
            [1] => 4
        )

)

Javascript

function combine(arr) {
    var r = [];
    (function f(t, a, depth, end) {
        if (depth == end) return t.length ? r.push(t) : r;
        for (var i = 0; i < a[depth].length; i++) {
            f(t.concat(a[depth][i]), a, depth + 1, end);
        }
    })([], arr, 0, arr.length);
    return r;
}
var arr = [
    ['1', '2'],
    ['3', '4']
];
var res = combine(arr);
console.log(res);
// preview
[["1","3"],["1","4"],["2","3"],["2","4"]]