<p>I have a list of email address which I want to distribute evenly by domain.</p>

<p>For example:</p>

<p>let the list be, </p>

<pre><code>a@a.com
b@a.com
c@a.com
a@b.com
b@b.com
c@c.com
</code></pre>

<p>The output should be </p>

<pre><code>a@a.com
a@b.com
c@c.com
b@a.com
b@b.com
c@a.com
</code></pre>

<p>The source list is not sorted by domain as in example, but can be sorted by domain, if that can help. What would be an efficient (single/two pass?) algorithm of doing this?</p>

<p>raj</p>

My starting attempt would be a hash map of linked lists, so that once all the domain collisions were grouped, you could iterate though the linked lists one at a time.
If that makes any sense.
The following code is completely
UNTESTED
, and I know there is a bunch of stuff not right in the second loop, but it was faster than trying to explain further.
```
```
$sortedList = array();
$tempList
$emailList = array('a@a.com', 'b@a.com', 'c@b.com', 'd@b.com', 'e@c.com', 'f@a.com');

$emailCount = 0;
foreach ( $emailList as $email ) {
    list($username, $domain) = explode('@', $email);
    $tempList[$domain][] = $user;
    $emailCount++;
}

for ( $i = 0; $i < $emailCount; $i++ ) {
    $listIndex = $i % count($tempList);
    if ( !empty($tempList[$listIndex]) ) {
        $sortedList[] = $tempList[$listIndex][0];
        unset($tempList[$listIndex][0]);
    } else {
        unset$tempList[$listIndex]);
    }
}
```
```