Last active
January 23, 2019 21:50
-
-
Save hemanthpai/a69c25d5d4266a21878eaec6f84f8a78 to your computer and use it in GitHub Desktop.
Card Dealer Solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { number, element } from "prop-types"; | |
/** | |
* Shuffle an array in place | |
* @param a Array to shuffle | |
*/ | |
function shuffleArray(a: any[]) { | |
// Iterate over the array | |
for (let i = a.length; i; i--) { | |
// Get next index | |
let j = Math.floor(Math.random() * i); | |
// Swap positions | |
[a[i - 1], a[j]] = [a[j], a[i - 1]]; | |
} | |
} | |
/** | |
* Suit, CardNumber | |
* 0=clubs, 1=diamonds, 2=hearts, 3=spades | |
*/ | |
export enum Suit { | |
Clubs, | |
Diamonds, | |
Hearts, | |
Spades | |
} | |
export enum CardNumber { | |
Ace, | |
Two, | |
Three, | |
Four, | |
Five, | |
Six, | |
Seven, | |
Eight, | |
Nine, | |
Ten, | |
Jack, | |
Queen, | |
King | |
} | |
type Card = [number, number]; | |
export class Dealer { | |
deck: Card[]; | |
constructor() { | |
let suitIndex; | |
let numberIndex; | |
this.deck = []; | |
for(suitIndex=0; suitIndex < 4; suitIndex++) { | |
for(numberIndex=0; numberIndex < 13; numberIndex++) { | |
this.deck.push([suitIndex, numberIndex]); | |
} | |
} | |
shuffleArray(this.deck); | |
} | |
dealHand(num:number) { | |
if(num > this.deck.length || num < 0) { | |
throw Error("Invalid number of cards requested!"); | |
} | |
return this.deck.splice(0, num); | |
} | |
getLength() : number { | |
return this.deck.length; | |
} | |
readCard(card:Card) { | |
return CardNumber[card[1]] + ' of ' + Suit[card[0]]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment