【发布时间】:2011-12-26 22:56:22
【问题描述】:
好的,伙计们,我需要为摄影比赛实现这个...我有一组主要的 N 张图片,我需要生成这些图片的大小为 2 的排列而不重复,例如:
foo.png VS bar.png
等于
bar.png VS foo.png
另一件事,我不能每次都预先生成所有排列,所以我需要一个函数,在给定前一个排列的情况下,将返回下一个排列(如果可能的唯一排列结束,则返回 NULL)。
我用下面的 PHP 函数解决了这个问题:
function getNextPermutation( $aPermutableItems, $iPermutationSize, $aPreviousPermutation = NULL )
{
$aNextPermutation = $aPreviousPermutation;
$iLastIndex = $iPermutationSize - 1;
$iPermutableItems = count($aPermutableItems);
// Any previous permutation ?
if( $aPreviousPermutation )
{
// Loop the elements backwards
for( $i = $iLastIndex; $i >= 0; $i-- )
{
// Can the current element be incremented without reaching the limit ?
if( ++$aNextPermutation[ $i ] >= $iPermutableItems )
{
// Increment the previous element
$iPrevValue = ++$aNextPermutation[ $i - 1 ];
// Reset the current element with the value of the previous plus one
$iNextValue = $aNextPermutation[ $i ] = $iPrevValue + 1;
// Skip the previous element because it was just incremented
$i--;
// If one of the two elements reached the limit, we are in the exit condition
if( $iPrevValue >= $iPermutableItems || $iNextValue >= $iPermutableItems )
return FALSE;
}
// Limit still to be reached for the i-th element, skip previous ones
else
break;
}
}
// Am i able to generate the first permutation ?
else if( $iPermutationSize <= $iPermutableItems )
$aNextPermutation = range( 0, $iLastIndex );
// Permutation impossible to generate because we don't have enough elements in the main set
else
$aNextPermutation = FALSE;
return $aNextPermutation;
}
这样:
$iPerm = 0;
$aPrev = NULL;
$aItems = array( 0, 1, 2, 3, 4 );
while( ($aPrev = getNextPermutation( $aItems, 2, $aPrev )) != FALSE )
{
echo sprintf( "%2d : %s\n", $iPerm++, implode( ', ', $aPrev ) );
}
将输出:
0 : 0, 1
1 : 0, 2
2 : 0, 3
3 : 0, 4
4 : 1, 2
5 : 1, 3
6 : 1, 4
7 : 2, 3
8 : 2, 4
9 : 3, 4
现在,我真的很想给它添加一些熵...我的意思是,如您所见,组合中的第一项经常重复( 0,1 0,2 0,3 ),并且就我而言,这并不好,因为我会看到 4 个连续排列的相同图片。
有没有办法修改(或重新实现)我的算法以具有类似(例如)的东西:
0 : 0, 1
1 : 1, 2
2 : 0, 3
3 : 3, 4
4 : 0, 2
5 : 1, 3
6 : 0, 4
7 : 2, 3
8 : 2, 4
9 : 1, 4
显然,我不能只打乱排列数组,因为正如我所写,我没有整个排列数组,而只有前一个排列,一旦应用我的算法就会给我下一个排列。
PS:每个挑战我有大约 500 张照片,因此存储位掩码或类似的东西是不可接受的。
谢谢。
【问题讨论】:
标签: php algorithm unique permutation