"Blackjack Anyone?"
Given an input file containing 1000 random blackjack hands between 3 players (here: blackjack.txt), calculate the number of blackjacks encountered for any player in all games.
A blackjack is defined as an Ace of any suit and a 10 valued card (Jack, Queen ,King or 10) of any suit.
The input file looks like this: (as an example)
This means that player one has a 4 of hearts and a 5 of clubs; player 2 has an Ace of Diamonds and a Jack of Hearts (which counts as a blackjack); player 3 has a 9 of Clubs and a 10 of Hearts.
For the purpose of this problem, it is known that there is a standard 52 card deck which is reshuffled for each new game.
Now this was a fun one... I recommend going slow and double checking everything, first get a copy of the file, then tear apart into hands, then check each hand to see if matches the rules for blackjack - If so then add to a counter :D
Awnser:
Blackjack wins = 0
Source:
include(MISC.'fn.fetch.php'); function checkhand($card1, $card2){ $blackjack = 0; if((substr($card1, 0, 1)== "A") || (substr($card2, 0, 1)== "A")){ // if either card is an ace if((strlen($card1) == 3) || (strlen($card2) == 3) || // if other card is a 10 (substr($card1, 0, 1)== "J") || (substr($card2, 0, 1)== "J") || // other a jack (substr($card1, 0, 1)== "Q") || (substr($card2, 0, 1)== "Q") || // other a queen (substr($card1, 0, 1)== "K") || (substr($card2, 0, 1)== "K") ){ // other a king $blackjack = 1; } } return $blackjack; } function solution(){ $result = 0; $list = fetch('http://www.cstutoringcenter.com/problems/files/blackjack.txt'); $lines = explode("\n", $list); foreach($lines as $handlist) { $hand = explode(" ", $handlist); for($i = 0; $i <= 5; $i += 2){ //loop 3 times, once per player if(isset($hand[$i]) && isset($hand[$i+1])){ $blackjack = checkhand(trim($hand[$i]), trim($hand[$i+1])); $color = ($blackjack == 1 ? "lightgreen" : "red"); $result += $blackjack; echo "(".trim($hand[$i])." ".trim($hand[$i+1]).") "; } } } echo "
Blackjack wins = ".$result.""; }