按模板生成组合

2022-12-28 12:28:22 浏览数 (1)

收集了一些方法,用来生产域名然后查询注册信息。

代码语言:javascript复制
<?php

ini_set('memory_limit','10000M');
function combinations($arrays, $i = 0) {
    if (!isset($arrays[$i])) {
        return array();
    }
    if ($i == count($arrays) - 1) {
        return $arrays[$i];
    }
    
    //     get combinations from subsequent arrays
        $tmp = combinations($arrays, $i   1);
    
    $result = array();
    
    //     concat each array from tmp with each element from $arrays[$i]
        foreach ($arrays[$i] as $v) {
        foreach ($tmp as $t) {
            $result[] = is_array($t) ? 
                            array_merge(array($v), $t) :
                            array($v, $t);
        }
    }
    
    return $result;
}


/**
* Generate all the possible combinations among a set of nested arrays.
 *
 * @param array $data  The entrypoint array container.
 * @param array $all   The final container (used internally).
 * @param array $group The sub container (used internally).
 * @param mixed $val   The value to append (used internally).
 * @param int   $i     The key index (used internally).
 */
 function generate_combinations(array $data, array &$all = array(), array $group = array(), $value = null, $i = 0)
 {
    $keys = array_keys($data);
    if (isset($value) === true) {
        array_push($group, $value);
    }
    
    if ($i >= count($data)) {
        array_push($all, $group);
    }
    else {
        $currentKey     = $keys[$i];
        $currentElement = $data[$currentKey];
        foreach ($currentElement as $val) {
            generate_combinations($data, $all, $group, $val, $i   1);
        }
    }
    
    return $all;
}

function cartesian_product($a) {
    $result = array(array());
    foreach ($a as $list) {
        $_tmp = array();
        foreach ($result as $result_item) {
            foreach ($list as $list_item) {
                $_tmp[] = array_merge($result_item, array($list_item));
            }
        }
        $result = $_tmp;
    }
    return $result;
}

function get_combinations($arrays) {
    $result = array(array());
    foreach ($arrays as $property => $property_values) {
        $tmp = array();
        foreach ($result as $result_item) {
            foreach ($property_values as $property_value) {
                $tmp[] = array_merge($result_item, array($property => $property_value));
            }
        }
        $result = $tmp;
    }
    return $result;
}


$data = array(
    range('a', 'z'),
    range('a', 'z'),
    range('a', 'z'),
    range('a', 'z'),
    range('a', 'z'),
);


$combos = generate_combinations($data);
echo sizeof($combos);
echo "n";
echo "not real: ".(memory_get_peak_usage(false)/1024/1024)." MiBn";
echo "real: ".(memory_get_peak_usage(true)/1024/1024)." MiBnn";

0 人点赞