9/26/2012

Thirty One

Problem Statement

Thirty One is a card game for 2 or more players. The game can be played with one or more decks of standard cards. The aim of the game is to try and make the value of your hand as close to 31 points as possible without going over 31 points. A hand consists of exactly 3 cards.

Each number card (2, 3, ... 9, 10) is worth the value written on the card; Jack (J), Queen (Q) and King (K) are all worth 10; while an Ace (A) is worth either 1 or 11 depending on which will give a greater total without going over 31 points. There is one exception however; if a hand consists of 3 identical cards then the value of that hand automatically becomes 30.5 points.

Each element in hands will contain exactly three cards, where cards are separated by exactly one space. For example "A 10 K" is a hand consisting of Ace, 10 and King. The value of this hand is 11 + 10 + 10 = 31. Note that we chose Ace to be 11 and not 1 since that gives us a greater total without exceeding 31.

Given a String[] of players' hands return the index of the winning player, where element i (0-indexed) in hands belongs to player i. If two or more players are tied for the lead then return the player with the lower index.



public class ThirtyOne {
 public static int findWinner(String[] hands) {
  int totalPlyrs = hands.length;
  float[] totalPoints = new float[totalPlyrs];
  int[] numOfAs = new int[totalPlyrs];
  float maxPoint = 0.0f;
  int maxLoc = totalPlyrs - 1;
  for (int i=0; i<totalPlyrs; i++) {
   totalPoints[i] = 0;
   numOfAs[i] = 0;
   String hand = hands[i];
   for (int j=0; j<hand.length(); j++) {
    if (hand.length() == 8 || (hand.length() == 5 && hand.charAt(0) == hand.charAt(2) && hand.charAt(2) == hand.charAt(4))) {
     totalPoints[i] = 30.5f;
     break;
    }
   
    if (hand.charAt(j) == 'J' || hand.charAt(j) == 'Q' || hand.charAt(j) == 'K') {
     totalPoints[i]+=10;
    }
    else if (hand.charAt(j) >= '2' && hand.charAt(j) <= '9') {
     totalPoints[i]+= (hand.charAt(j) - '0');
    }
    else if (hand.charAt(j) == '1') {
     if (i<hand.length()-1) {
      if (hand.charAt(j+1) == '0') {
       totalPoints[i]+=10;
       j++;
      }
      else {
       totalPoints[i]+=1;
      }
     }
     else {
      totalPoints[i]+=1;
     }
    }
    
    else if (hand.charAt(j) == 'A') {
     totalPoints[i]+=11;
     numOfAs[i]++;
    }
   }
   
   while (numOfAs[i] > 0) {
    if (totalPoints[i] > 31) {
     numOfAs[i]--;
     totalPoints[i]-=10;
    }
    else {
     break;
    }
   }
   
  }
  
  for (int i=totalPlyrs-1; i>0; i--) {
   if (totalPoints[i] >= maxPoint && totalPoints[i]<=31) {
    maxLoc = i;
    maxPoint = totalPoints[i];
   }
  }
  return maxLoc; 
 }
}

No comments:

Post a Comment