Using PHP, randomly pair up group of items, not pa

2020-02-07 05:37发布

Assume you have a set of items in an array.

A, B, C, D, E, F, G, H

Using PHP, how would you randomly pair the letters together without pairing them with a duplicate of themselves?

Such as this:

 A->pairedLetter = G
 B->pairedLetter = C
 C->pairedLetter = E
 D->pairedLetter = A
 E->pairedLetter = B
 F->pairedLetter = D
 G->pairedLetter = F

and so on...

EDIT: Oh, and also, If A is paired with F, F can NOT be paired with A. So there will have to be as many relationships as there are items.

7条回答
虎瘦雄心在
2楼-- · 2020-02-07 06:11

Using the shuffle function on the array and checking that the mappings are valid (A doesn't map to A and that if A maps to B then B doesn't map to A). The following should do what you want:

$values = array('A','B','C','D','E','F','G');
$new_values = array('A','B','C','D','E','F','G');

$random = shuffle($new_values);
//randomly shuffle the order of the second array
$mappings = array();

$validMappings = false;
//continue to retry alternative mappings until a valid result is found
while(!$validMappings) {
   //set the mappings from $values to $new_values
   for($i = 0; $i < count($values); $i++) {
        $mappings[$values[$i]] = $new_values[$i];
    }

    $validMappings = true;
    //check validity of the current mapping
    foreach ($mappings as $key=>$value) {
        if($mappings[$key] == $mappings[$value]) {
            $validMappings = false;
            break;
        }
    }
    //if false shuffle the new values and test again
    if(!$validMappings) {
        $random = shuffle($new_values);
    }
}
print_r($mappings);
查看更多
登录 后发表回答