0

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
        [1] => a vs. c
        [2] => b vs. c
    )

2 Answers 2

3

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.

1

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 );
1
  • Thanks. Despite it not being as elegant, I actually used your version since it was more straight forward (for me) in php.
    – Ryan
    Jul 29, 2011 at 19:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.