PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
Copy Clear
Copy Format Clear
<?php printf("Current PHP version: %s \n", phpversion()); class Match { protected $startingUsers = ["User1", "User2", "User3", "User4", "User5"]; protected $pairs = []; protected $matchedUsers = 0; function getPairs(): array { if ($this->generateUsers($this->startingUsers)) { return $this->pairs; } return []; } function generateUsers(array $defaultUsers, array $updatedUsers = []): bool { $users = !empty($updatedUsers) ? $updatedUsers : $defaultUsers; if (count($users) > 1) { if ($this->matchedUsers !== count($this->startingUsers)) { // Pick random user and match with current user. Reset array and repeat until 1 or no users left. $randomUserIndex = rand(1, count($users) - 1); $this->pairs[] = [$users[0], $users[$randomUserIndex]]; unset($users[$randomUserIndex]); unset($users[0]); // Remove pair from list so they can't be assigned again. Reset array for 0 based index $users[0] $newUsers = array_values($users); $this->generateUsers($this->startingUsers, $newUsers); $this->matchedUsers += 2; } } // If only one user remains can't allocate a Pair if (count($users) === 1) { $orderedUsers = array_values($users); $this->pairs[] = [$orderedUsers[0], "No Pair"]; return true; } return true; } } $match = new Match(); foreach ($match->getPairs() as $pair) { echo "$pair[0] gets $pair[1]"; echo "\n"; }
Show:  
Copy Clear