我想从整数集(n)中随机分组整数(r)。例如n = 1,2,3,4,5,6和r = 3,我希望输出为{1,2,3} {4,5,6} so-on ...但如果使用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))."\n\n";
echo 'The following is the combinations array'."\n\n";
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;
}
答案 0 :(得分:0)
我不是PHP人,所以这里没有代码。但至于算法,我认为你需要的是: