来自整数"n"集合的 r 的随机组合,不重复

  • 本文关键字:组合 随机 集合 整数 php math
  • 更新时间 :
  • 英文 :


我想从整数集(n(中随机分组整数(r(。例如 n = 1,2,3,4,5,6 和 r = 3,我希望输出为 {1,2,3} {4,5,6} 依此类推......但是如果在一个组中使用 1,我不希望它使用另一个组。等等。我想要一个独特的组合作为输出。我如何在 PHP 中执行此操作?

此代码给出所有组合,没有随机性

// view the real output 
header('Content-Type: text/plain'); 
// your string 
$letters = 'RAT'; 
// convert to array 
$letters_array = array("RAT1 ", "RAT2 ", "RAT3 ", "RAT4 ", "RAT5 ","RAT6 ", "RAT7", "RAT8", "RAT9", "RAT10");
echo 'The number of two charcter combinations from that string is '.count($result = get_combos($letters_array, 3))."nn";
echo 'The following is the combinations array'."nn"; 
print_r(array_2d_to_1d($result)); 
function get_combos($input, $combo_length) 
{ 
    $input = array_values($input); 
    $code = ''; 
    $cnt = count($input); 
    $ret = array(); 
    $i0 = -1; 
    for($i=0;$i<$combo_length;++$i) 
    { 
        $k = 'i'.($i+1); 
        $code .= 'for($'.$k.'=$i'.$i.'+1; $'.$k.'< $cnt-'.($combo_length-$i-1).'; ++$'.$k.') '; 
    } 
    $code .= '$ret[] = array($input[$i'.implode('], $input[$i',range(1,$combo_length)).']);';
    eval($code); 
    return $ret; 
} 
function str_2_array($input) 
{ 
    for($i = 0, $len = strlen($input); $i < $len; $i++) 
    { 
        $rtn[] = $input[$i]; 
    } 
    return $rtn; 
} 
function array_2d_to_1d($input) 
{ 
    foreach($input as $key => $value) 
    { 
        $rtn[$key] = implode($value); 
    } 
    return $rtn; 
} 

我不是PHP的人,所以这里不会有代码。但至于算法,我认为你需要的是:

  1. (可选(从源数组中删除非唯一值
  2. 执行数组的随机洗牌
  3. 将洗牌数组切成所需长度的子数组。

最新更新