Skip to content

Instantly share code, notes, and snippets.

@forkbombe
Created October 3, 2018 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save forkbombe/2dd9f62b26e2ce17efb3621e5f5d885a to your computer and use it in GitHub Desktop.
Save forkbombe/2dd9f62b26e2ce17efb3621e5f5d885a to your computer and use it in GitHub Desktop.
I was asked in a job interview to deal 5 random playing cards to n number of players
<?php
class Deck {
protected $suits = array('Hearts', 'Spades', 'Clubs', 'Diamonds');
protected $ranks = array('Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King');
public function cards() {
$cards = [];
foreach($this->suits as $suit) {
foreach($this->ranks as $rank) {
$cards[] = $rank . " of " . $suit;
}
}
return $cards;
}
}
class Game extends Deck {
// Index of card array
private $index = 0;
private $cards = [];
public function shuffle() {
// Assign cards to variable
$this->cards = $this->cards();
// Randomise cards
uksort($this->cards, function() { return rand() > rand(); });
// Rebase cards array
$this->cards = array_values($this->cards);
}
public function nextCard() {
// Increment index
$this->index++;
// Return next index in array
return $this->cards[$this->index];
}
public function deal($players) {
$output = [];
// For each player
for($i=1;$i<=$players;$i++) {
// Add 5 cards
for($c=0;$c<5;$c++) {
$output[$i][] = $this->nextCard();
}
}
return $output;
}
}
$game = new Game();
$game->shuffle();
$deal = $game->deal(3);
print_r($deal);
// Deal 5 cards to `n` number of players
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment