How can I efficiently iterate through pairs within an array without duplicating?
Assume I have 3 teams that each need to play each other once. How can one efficiently iterate through them to schedule matches without duplicates?
$teams = range('a', 'c');
$games = array();
foreach ($teams as $t1)
foreach ($teams as $t2)
if ($t1 != $t2)
$games[] = $t1 . ' vs. ' . $t2;
print_r($games);
Results in:
Array
(
[0] => a vs. b
[1] => a vs. c
[2] => b vs. a <-- Duplicate of [0]
[3] => b vs. c
[4] => c vs. a <-- Duplicate of [1]
[5] => c vs. b <-- Duplicate of [3]
)
How can one efficiently avoid the duplicate matches?
The answer should yield:
Array
(
[0] => a vs. b
开发者_Go百科 [1] => a vs. c
[2] => b vs. c
)
Generically:
Container C;
for (i = 0; i < C.size; ++i)
{
for (j = i + 1; j < C.size; ++j)
{
/* have unique unordered set {i, j} */
}
}
If you want the diagonal entries (i, i)
, start at j = i
.
This solution isn't as elegant as @Kerrek's, but it does the same job:
$teams = range('a', 'c');
$games = Array();
$matched = Array();
foreach ( $teams as $t1 )
foreach ( $teams as $t2 )
if ( $t1 != $t2 )
if ( !in_array( Array( $t1, $t2 ), $matched ) && !in_array( Array( $t2, $t1 ), $matched ) )
{
$games[] = $t1 . ' vs. ' . $t2;
$matched[] = Array( $t1, $t2 );
}
print_r( $games );
精彩评论