Demo entry 6363575

Prob Project

   

Submitted by anonymous on May 14, 2017 at 05:57
Language: Java. Code size: 13.3 kB.

import java.io.*;
import java.util.*;

public class PokerProbabilitiesAllStats
{
  // INPUTS:
  // the Player's cards in string form, in format "VS VS" where the "V"s are a
  // value character (23456789TJQKA) and the "S"s are a suit character (SHDC)
  public static final String MYCARDS = "5H JH";
  
  // number of opponents the Player is playing against (minimum 1 opponent, maximum 10 opponents)
  public static final int NUMOFOPPONENTS = 7;
  
  // number of simulations to to run (obviously should be > 0, and should be > 100 for get a correct loading bar)
  public static final int NUMOFSIMS = 10000;
  
  // a String with all possible card values in order (to be used later)
  public static final String VALUES = "23456789TJQKA";
  // a String with all card suits in order (to be used later)
  public static final String SUITS = "SHDC";
  
  // used to store the list of hands read from the text file "handRankings.txt", in order from lowest to highest ranked
  ArrayList<String> handRankings = new ArrayList<String>();
  // the game deck; program starts by filling the list with the integers 0 to 51
  ArrayList<Integer> cardInts = new ArrayList<Integer>();
  
  // integer representation of the Player's first and second cards
  int myCInt1;
  int myCInt2;
  
  // program executed first - creates an object and then runs the "run" method
  public static void main(String[] args) throws Exception
  {
    PokerProbabilitiesAllStats ppAS = new PokerProbabilitiesAllStats();
    ppAS.run(args);
  }
  
  // the setup method of the program.  Makes the deck, figures out what the Player's 2 starting
  // cards were as integers, removes those from the deck, and then calls the simulation method.
  public void run(String[] args) throws Exception
  {
    makeDeck();
    
    // read the list of hands from the text file, and store them in order in the handRankings ArrayList
    System.out.print("Generating array list of hand rankings...");
    Scanner sc = new Scanner(new File("handRankings.txt"));
    String tempLine = "";
    while (sc.hasNextLine())
    {
      tempLine = sc.nextLine();
      handRankings.add(tempLine);
    }
    System.out.println("done.");
    
    // calulate the integer equivalent of the Player's two starting cards, given at the start of the program...
    myCInt1 = VALUES.indexOf(MYCARDS.charAt(0))*4 + SUITS.indexOf(MYCARDS.charAt(1));
    myCInt2 = VALUES.indexOf(MYCARDS.charAt(3))*4 + SUITS.indexOf(MYCARDS.charAt(4));
    // ...and then remove those 2 cards from the deck
    if (myCInt1 < myCInt2)
    {
      cardInts.remove(myCInt2);
      cardInts.remove(myCInt1);
    }
    else
    {
      cardInts.remove(myCInt1);
      cardInts.remove(myCInt2);
    }
    runSimulations(NUMOFSIMS);
  }
  
  // the simulation method..  Initates storage places for our data (W/T/L and count of number of best hands (straight flushes,
  // full houses, etc)), then runs the simulation the given number of times, and then prints out the collected data.
  public void runSimulations(int numberOfSimulations)
  {
    Random rand = new Random();
    int[] stats = {0,0,0}; // tally of the Win/Tie/Loss counts
    int[] myBestHands = {0,0,0,0,0,0,0,0,0,0};// tally of the number of different best hands obtained by the Player
    int[] rankIndices = {7461,7452,7296,7140,5863,5853,4995,4137,1277,0};
    System.out.println("Running simulation...");
    System.out.println("[|        ||        ||        ||        ||        ||        ||        ||        ||        ||        |]");
    System.out.print("[");
    int[] opponentCards = {-1,-1, -1,-1, -1,-1, -1,-1, -1,-1, -1,-1, -1,-1, -1,-1, -1,-1, -1,-1};
    for (int simNumber = 0; simNumber < numberOfSimulations; simNumber++)
    {
      /* what do we want to do for each simulation
       * [1] - get 5 random cards for the board
       * [2] - what's my best ranking with my 2 cards and the 5 board cards we just got
       * [3] - keep track of the number of each type of hand we've come across (add 1 to the right place)
       * [4] - initiate a place where we can save what their best ranking is (*STORAGE*)
       * [5] - for each opponent:
       *     [A] - give him/her 2 random cards (and remove them from the deck)
       *     [B] - get their best ranking with those 2 cards and the 5 board cards
       *     [C] - if their best ranking is better than any we've seen before (for the other opponents), save it in *STORAGE*
       *     [D] - Save their cards (so that later we can add them back in)
       *     [E] - If they beat our best ranking, leave cuz we're done
       * [6] - now we've gone through all the opponents (or broken out because they've beat us)
       * [7] - Check if the best hand that we stored beats us or nah, and keep track of wins/ties/losses
       * [8] - put all the board cards and the opponent back in the deck
       */
      
      if (((simNumber + 1) % (numberOfSimulations/100)) == 0)
        System.out.print("|");
      // [1]
      Integer bc1 = cardInts.remove(rand.nextInt(50));
      Integer bc2 = cardInts.remove(rand.nextInt(49));
      Integer bc3 = cardInts.remove(rand.nextInt(48));
      Integer bc4 = cardInts.remove(rand.nextInt(47));
      Integer bc5 = cardInts.remove(rand.nextInt(46));
      
      // [2]
      int myBestRanking = getBestRanking(new int[]{myCInt1, myCInt2, bc1, bc2, bc3, bc4, bc5}, 7462);
      
      // [3]
      for (int i = 0; i < 10; i++)
      {
        if (myBestRanking >= rankIndices[i])
        {
          myBestHands[i]++;
          i = 10;
        }
      }
      
      // [4]
      int theirBestRanking = 0;
      
      // [5]
      for (int i = 0; i < NUMOFOPPONENTS; i++)
      {
        // [A]
        int opC1 = cardInts.remove(rand.nextInt(45-(2*i)));
        int opC2 = cardInts.remove(rand.nextInt(44-(2*i)));
        
        // [B]
        int tempTheirBestRanking = getBestRanking(new int[]{bc1, bc2, bc3, bc4, bc5, opC1, opC2}, myBestRanking);
        
        // [C]
        if (tempTheirBestRanking > theirBestRanking)
          theirBestRanking = tempTheirBestRanking;
        
        // [D]
        opponentCards[2*i] = opC1;
        opponentCards[2*i+1] = opC2;
        
        // [E]
        if (theirBestRanking > myBestRanking)
          i = NUMOFOPPONENTS;
      }
      // [6] (simulation is now done with looking at opponents)
      
      // [7]
      if (myBestRanking > theirBestRanking)
        stats[0]++;
      else if (myBestRanking == theirBestRanking)
        stats[1]++;
      else
        stats[2]++;
      
      // [8]
      for (int i = 0; i < 20; i++)
      {
        if (opponentCards[i] != -1)
        {
          cardInts.add(opponentCards[i]);
          opponentCards[i] = -1;
        }
      }
      cardInts.add(bc1);
      cardInts.add(bc2);
      cardInts.add(bc3);
      cardInts.add(bc4);
      cardInts.add(bc5);
    }
    System.out.println("]");
    
    // Now, print out the collected data
    System.out.println();
    System.out.println();
    System.out.println("My starting cards: " + MYCARDS);
    System.out.println();
    System.out.println("Number of Opponents: " + NUMOFOPPONENTS);
    System.out.println();
    System.out.println("Total number of simulations: " + numberOfSimulations);
    System.out.println();
    printPercentageLine("  Wins: ", stats[0], numberOfSimulations);
    printPercentageLine("  Ties: ", stats[1], numberOfSimulations);
    printPercentageLine("Losses: ", stats[2], numberOfSimulations);
    System.out.println();
    
    ArrayList<String> rankingStrs = new ArrayList<String>();
    rankingStrs.add("    Royal Flush: ");
    rankingStrs.add(" Straight Flush: ");
    rankingStrs.add(" Four of a Kind: ");
    rankingStrs.add("     Full House: ");
    rankingStrs.add("          Flush: ");
    rankingStrs.add("       Straight: ");
    rankingStrs.add("Three of a Kind: ");
    rankingStrs.add("       Two Pair: ");
    rankingStrs.add("           Pair: ");
    rankingStrs.add("      High Card: ");
    for (int i = 0; i < 10; i++)
    {
      int amount = myBestHands[i];
      printPercentageLine(rankingStrs.get(i), amount, numberOfSimulations);
    }
    System.out.println();
    System.out.println();
    System.out.println();
    System.out.println("TEXT FOR EXCEL:");
    System.out.println();
    System.out.println("" + MYCARDS + "\t<--My starting Cards");
    System.out.println("" + NUMOFOPPONENTS + "\t<--Num of Opponents");
    System.out.println("" + numberOfSimulations + "\t<--Num of Simulations");
    System.out.println();
    System.out.println("" + stats[0] + "\t<--Wins");
    System.out.println("" + stats[1] + "\t<--Ties");
    System.out.println("" + stats[2] + "\t<--Losses");
    System.out.println();
    System.out.println("" + myBestHands[0] + "\t<--Royal Flush");
    System.out.println("" + myBestHands[1] + "\t<--Straight Flush");
    System.out.println("" + myBestHands[2] + "\t<--Four of a Kind");
    System.out.println("" + myBestHands[3] + "\t<--Full House");
    System.out.println("" + myBestHands[4] + "\t<--Flush");
    System.out.println("" + myBestHands[5] + "\t<--Straight");
    System.out.println("" + myBestHands[6] + "\t<--Three of a Kind");
    System.out.println("" + myBestHands[7] + "\t<--Two Pair");
    System.out.println("" + myBestHands[8] + "\t<--Pair");
    System.out.println("" + myBestHands[9] + "\t<--High Card");
  }
  
  // This method is solely used to print out the collected data in an easy to read format
  private void printPercentageLine(String beginning, int value, int total)
  {
    System.out.print(beginning);
    
    int lengthOfPadding = ("" + total).length();
    String padding = "";
    for (int i = 0; i < lengthOfPadding; i++)
      padding += " ";
    String amountStr = (padding + value).substring((padding + value).length() - lengthOfPadding);
    System.out.print(amountStr + "   ");
    
    int rounded =  (int) Math.round((1000000.0 * value)/total);
    String roundedStr = ("" + rounded);
    if (rounded == 0)
      System.out.println(" 0.0000%");
    else if (rounded < 10)
      System.out.println(" 0.000" + roundedStr + "%");
    else if (rounded < 100)
      System.out.println(" 0.00" + roundedStr + "%");
    else if (rounded < 1000)
      System.out.println(" 0.0" + roundedStr + "%");
    else if (rounded < 10000)
      System.out.println(" 0." + roundedStr + "%");
    else if (rounded < 100000)
      System.out.println(" " + roundedStr.charAt(0) + "." + roundedStr.substring(1) + "%");
    else
      System.out.println(roundedStr.substring(0,2) + "." + roundedStr.substring(2) + "%");
  }
  
  // fill our imaginary 'deck'
  private boolean makeDeck()
  {
    System.out.print("Generating \"deck\"...");
    for (int i = 0; i < 52; i++)
      cardInts.add(new Integer(i));
    System.out.println("done.");
    return true;
  }
  
  // given 7 cards, for each combination of 5 cards, find it's rank, and then keep track of the highest ranked hand
  // seen so far. If at any point the method comes across 5 cards with a rank better than rankToBeat, return that
  // ranking.  This method is called in 2 places: [1] when calculating the Player's best hand, and [2] when
  // calculating the opponents best hand.  When [1], the program needs to find the best hand possible, so the method
  // is given an unbeatable rankToBeat input, so the method never finds a set of five cards that beats rankToBeat so
  // instead will return the highest rank.  When [2], all the program cares about is did the opponent beat us, so
  // the method is given a rankToBeat equal to the Player's best rank, and if any five-card hand beats rankToBeat,
  // we know an opponent beat the Player, so we can return that opponent's hand rank and exit the method.
  public int getBestRanking(int[] cards, int rankToBeat)
  {
    Arrays.sort(cards);
    int bestRankingSoFar = 0;
    for (int c1 = 0; c1 < 3; c1++)
    {
      for (int c2 = c1 + 1; c2 < 4; c2++)
      {
        for (int c3 = c2 + 1; c3 < 5; c3++)
        {
          for (int c4 = c3 + 1; c4 < 6; c4++)
          {
            for (int c5 = c4 + 1; c5 < 7; c5++)
            {
              int thisRanking = getRank(cards[c1], cards[c2], cards[c3], cards[c4], cards[c5]);
              if (thisRanking > rankToBeat)
                return thisRanking;
              if (thisRanking > bestRankingSoFar)
                bestRankingSoFar = thisRanking;
            }
          }
        }
      }
    }
    return bestRankingSoFar;
  }
  
  // given 5 cards, calculates the rank of those 5 cards, using the handRankings ArrayList.
  public int getRank(int c1, int c2, int c3, int c4, int c5)
  {
    String handStr = "";
    if (c1 % 4 == c2 % 4 && c2 % 4 == c3 % 4 && c3 % 4 == c4 % 4 && c4 % 4 == c5 % 4)
      handStr = "F";
    else
      handStr = "N";
    handStr += ("" + VALUES.charAt(c1/4) + VALUES.charAt(c2/4) + VALUES.charAt(c3/4)
                  + VALUES.charAt(c4/4) + VALUES.charAt(c5/4));
    return handRankings.indexOf(handStr);
  }
}

This snippet took 0.02 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).