Mon 12 Sep 2011
Over the weekend, a local instructional tech company (Instructure) had a computer programming contest. I was down hiking in southern Utah, so I didn’t get to be a part of the coding mayhem. Up for grabs was $10,485.76. It’s an agreeable publicity trick that CEO Josh Coates has pulled before (last time it was for a company called Mozy, also in Utah County.) I previously solved one of the Mozy contest sample questions for you, and today I’ll do the same work with problem #1 of the Instructure coding challenge sample set:
Given a variable number of playing cards, form the best hand that does not exceed 21. The cards are in the set [23456789JQKA], where 2-9 are worth their face value, J Q and K are worth 10, and A can be selected to be worth either 1 and 11. In this scenario, you are only playing with one suit, so there is never more than one of each card.
Input:
The first line is a single number, which is the number of lines to follow. Each line after that is a sequence of characters in the above set.
Output:
For each input line of cards, output the highest possible score that does not exceed 21.
Example:
STDIN:
4
296J
85
A37
475ASTDOUT:
21
13
21
20
And here is my solution:
-
function pc_array_power_set($array)
-
{
-
// src: http://docstore.mik.ua/orelly/webprog/pcook/ch04_25.htm#phpckbk-CHP-4-EX-5
-
foreach ($array as $element)
-
foreach ($results as $combination)
-
return $results;
-
}
-
function CardValue($array,$aceValue=1)
-
{
-
foreach($array as $key=>$card)
-
{
-
if ($card==’J'||$card==’Q'||$card==’K')
-
$newCardArray[]=10;
-
else if ($card==’A')
-
$newCardArray[]=$aceValue;
-
else
-
$newCardArray[]=$card;
-
}
-
$value=array_sum($newCardArray);
-
return $value;
-
}
-
$target=21;
-
$input=file($argv[1]);
-
for($x=1;$x<=trim($input[0]);$x++)
-
{
-
$row=trim($input[$x]);
-
$cardArray=str_split($row);
-
$aceValue=1;
-
if (in_array(‘A’,$cardArray)) $aceValue=11;
-
$combinations=pc_array_power_set($cardArray);
-
$value=CardValue($cardArray);
-
$highest=0;
-
if ($value!=21)
-
{
-
for ($y=0;$y<$aceValue;$y+=10)
-
{
-
foreach($combinations as $hand)
-
{
-
$value=CardValue($hand,$aceValue);
-
if ($value>$highest&&$value<=$target)
-
$highest=$value;
-
}
-
}
-
}
-
else
-
{
-
$highest=$value;
-
}
-
echo(“$highest\n”);
-
}
photo credits: http://www.butterfunk.com/image-12/N.E.R.D.htm