Prompt: Write a program that reads five cards from the user, then analyzes the cards and prints out the category of hand that they represent.
Poker hands are categorized according to the following labels: Straight flush, four of a kind, full house, flush, straight, three of a kind, two pairs, pair, high card.
I currently have my program set as follows, first prompting the user for 5 cards, 2-9, then sorting the cards in ascending order. I set up my program to prompt the user and then go through several if else statements calling methods. I am having issues though where its not identifying three or four of a kind.
Example, if I enter 1, 3, 2, 1, 1, it identifies it as TWO PAIRS instead of Three of a Kind.
Same for entering 1, 1,1, 1, 4, it identifies as three of kind instead of 4.
Any suggestions to my code?
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
final int HAND_SIZE = 5;
int[] hand = new int[HAND_SIZE];
getHand(hand); //Prompt user for hand
sortHand(hand);//Sort hand in ascending order
if(containsFullHouse(hand))
{
System.out.print("FULL HOUSE!");
}
else if(containsStraight(hand))
{
System.out.print("STRAIGHT!");
}
else if(containsFourOfAKind(hand))
{
System.out.print("FOUR OF A KIND!");
}
else if(containsThreeOfAKind(hand))
{
System.out.println("THREE OF A KIND!");
}
else if(containsTwoPair(hand))
{
System.out.println("TWO PAIRS!");
}
else if(containsPair(hand))
{
System.out.println("PAIR!");
}
else
System.out.println("High Card!");
}
public static void getHand(int[] hand)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter five numeric cards, 2-9, no face cards please");
for(int index = 0; index < hand.length; index++)
{
System.out.print("Card " + (index + 1) + ": ");
hand[index] = input.nextInt();
}
}
public static void sortHand(int[] hand)
{
int startScan, index, minIndex, minValue;
for(startScan = 0; startScan < (hand.length-1); startScan++)
{
minIndex = startScan;
minValue = hand[startScan];
for(index = startScan + 1; index <hand.length; index++)
{
if(hand[index] < minValue)
{
minValue = hand[index];
minIndex = index;
}
}
hand[minIndex] = hand[startScan];
hand[startScan] = minValue;
}
}
public static boolean containsPair(int hand[])
{
boolean pairFound = false;
int pairCount = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
pairCount++;
}
startCheck = hand[index];
}
if (pairCount == 1)
{
pairFound = true;
}
else if(pairCount !=1)
{
pairFound = false;
}
return pairFound;
}
public static boolean containsTwoPair(int hand[])
{
boolean twoPairFound = false;
int twoPairCount = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
twoPairCount++;
}
startCheck = hand[index];
}
if (twoPairCount == 2)
{
twoPairFound = true;
}
else if(twoPairCount != 2)
{
twoPairFound = false;
}
return twoPairFound;
}
public static boolean containsThreeOfAKind(int hand[])
{
boolean threeFound = false;
int threeKind = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
threeKind++;
}
startCheck = hand[index];
}
if(threeKind == 3)
{
threeFound = true;
}
else if(threeKind !=3)
{
threeFound = false;
}
return threeFound;
}
public static boolean containsStraight(int hand[])
{
boolean straightFound = false;
int straight = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 1)
{
straight++;
}
startCheck = hand[index];
}
if(straight == 4)
{
straightFound = true;
}
return straightFound;
}
public static boolean containsFullHouse(int hand[])
{
boolean fullHouseFound = false;
int pairCheck = 0;
int startPairCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startPairCheck) == 0)
{
pairCheck++;
}
startPairCheck = hand[index];
}
int threeOfKindCheck = 0;
int startThreeKindCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startThreeKindCheck) == 0)
{
threeOfKindCheck++;
}
startThreeKindCheck = hand[index];
}
if(pairCheck == 1 && startThreeKindCheck == 3)
{
fullHouseFound = true;
}
return fullHouseFound;
}
public static boolean containsFourOfAKind(int hand[])
{
boolean fourFound = false;
int fourKind = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
fourKind++;
}
startCheck = hand[index];
}
if(fourKind == 1)
{
fourFound = true;
}
else if(fourKind !=4)
{
fourFound = false;
}
return fourFound;
}
}
Some hints.
Start with the highest hand. This eliminates lots of logic.
I.e if you check for pairs first, than you also have to check to make sure that your pair is the only pair, and not three of a kind.
But if you already ruled all of those out your code would be check card 1and2 23 34 and 45.
Related
I have opened an account for Ridit, one of 7-years-old students learning Java at SPOJ. The first task i gave to him was PALIN -The Next Palindrome. Here is the link to this problem- PALIN- The next Palindrome- SPOJAfter i explained it to him, he was able to solve it mostly except removing the leading zeros, which i did. Following is his solution of the problem -
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Scanner in = new Scanner(System.in);
int t = Integer.parseInt(in.nextLine());
String[] numbersInString = new String[t];
for (int i = 0; i <t; i++) {
String str = in.nextLine();
numbersInString[i] = removeLeadingZeros(str);
}
for (int i = 0 ; i<t; i++) {
int K = Integer.parseInt(numbersInString[i]);
int answer = findTheNextPalindrome(K);
System.out.println(answer);
}
}catch(Exception e) {
return;
}
}
static boolean isPalindrome(int x) {
String str = Integer.toString(x);
int length = str.length();
StringBuffer strBuff = new StringBuffer();
for(int i = length - 1;i>=0;i--) {
char ch = str.charAt(i);
strBuff.append(ch);
}
String str1 = strBuff.toString();
if(str.equals(str1)) {
return true;
}
return false;
}
static int findTheNextPalindrome(int K) {
for(int i = K+1;i<9999999; i++) {
if(isPalindrome(i) == true) {
return i;
}
}
return -1;
}
static String removeLeadingZeros(String str) {
String retString = str;
if(str.charAt(0) != '0') {
return retString;
}
return removeLeadingZeros(str.substring(1));
}
}
It is giving correct answer in Eclipse on his computer, but it is failing in SPOJ. If someone helps this little boy in his first submission, it will definitely make him very happy. I couldn't find any problem with this solution... Thank you in advance...
This might be helpful
import java.io.IOException;
import java.util.Scanner;
public class ThenNextPallindrom2 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int t = 0;
Scanner sc = new Scanner(System.in);
if(sc.hasNextInt()) {
t = sc.nextInt();
}
sc.nextLine();
int[] arr, arr2;
while(t > 0) {
t--;
String s = sc.nextLine();
arr = getStringToNumArray(s);
if(all9(arr)) {
arr2 = new int[arr.length + 1];
arr2[0] = 1;
for(int i=0;i<arr.length;i++) {
arr2[i+1] = 0;
}
arr2[arr2.length -1] = 1;
arr = arr2;
} else{
int mid = arr.length/ 2;
int left = mid-1;
int right = arr.length % 2 == 1 ? mid + 1 : mid;
boolean left_small = false;
while(left >= 0 && arr[left] == arr[right]) {
left--;
right++;
}
if(left < 0 || arr[left] < arr[right]) left_small = true;
if(!left_small) {
while(left >= 0) {
arr[right++] = arr[left--];
}
} else {
mid = arr.length/ 2;
left = mid-1;
int carry = 1;
if(arr.length % 2 == 0) {
right = mid;
} else {
arr[mid] += carry;
carry = arr[mid]/10;
arr[mid] %= 10;
right = mid + 1;
}
while(left >= 0) {
arr[left] += carry;
carry = arr[left] / 10;
arr[left] %= 10;
arr[right++] = arr[left--];
}
}
}
printArray(arr);
}
}
public static boolean all9(int[] arr) {
for(int i=0;i<arr.length;i++) {
if(arr[i] != 9)return false;
}
return true;
}
public static void printArray(int[] arr) {
for(int i=0;i<arr.length;i++) {
System.out.print(arr[i]);
}
System.out.println();
}
public static int[] getStringToNumArray(String s) {
int[] arr = new int[s.length()];
for(int i=0; i<s.length();i++) {
arr[i] = Integer.parseInt(String.valueOf(s.charAt(i)));
}
return arr;
}
}
I'm currently writing a HugeInteger class that can take in 40 digits, and I have a few comparison tests that are already written. The thing I'm having most trouble with is adding and subtraction methods. I was able to get two values to add, but don't know how to implement a negate function if one of the values are negative. My subtraction method doesn't seem to work either.
public void add(HugeInteger hi) {
if (digits[NUM_DIGITS] < 0) {
negate();
this.subtract(hi);
}
int carry = 0;
for(int i = digits.length-1; i >=0 ;i--) {
int cur = this.digits[i] + hi.digits[i] + carry;
if (cur >= 10){
cur= cur-10;
resultAdd[i] = cur;
carry = 1;
} else{
resultAdd[i] = cur;
carry = 0;
}
}
StringBuilder builder = new StringBuilder();
int j=0;
for (int i : resultAdd) {
builder.append(i);
this.digits[j] = i;
j++;
}
this.hi = builder.toString().replace("0", "");
}
public void subtract(HugeInteger hi) {
for(int i = digits.length-1; i >=0 ;i--) {
if (this.digits[i] - hi.digits[i] < 0){
this.digits[i-1]--;
this.digits[i]+=10;
}
int cur = this.digits[i] - hi.digits[i];
this.digits[i] = cur;
}
StringBuilder builder = new StringBuilder();
int j=0;
for (int i : resultAdd) {
builder.append(i);
this.digits[j] = i;
j++;
}
this.hi = builder.toString().replace("0", "");
}
public void negate() {
if(this.positive){
this.positive = false;
} else{
this.positive = true;
this.hi = this.hi.replace("-", "");
}
}
I have a question. As an assignment we have to make the Nim game resolver using backtracking to predict which player is going to win based on the input on which player is going to start first (assuming that both players have a perfect decision rate).
Here is the code for the NimGame:
package Nim;
import java.util.ArrayList;
public class NimGame {
private int[] elements;
public NimGame(int[] elements) {
this.elements = new int[elements.length];
this.elements = elements;
}
public int NimSolver(boolean player) {
if (player == true && NimHelp(elements) == true) {
return 1;
} else if (player == false && NimHelp(elements) == true) {
return -1;
} else {
int score = 0;
int tmp = 0;
if (player == true) {
score = -1;
} else {
score = 1;
}
for (int i = 0; i < elements.length; i++) {
for (int j = 1; j <= elements[i]; j++) {
// Decrement element (Do thing)
elements[i] -= j;
// Backtrack
tmp = NimSolver(!player);
// SetScore
if (player == true && tmp > score) {
score = tmp;
} else if (player == false && tmp < score) {
score = tmp;
}
// Increment element (Undo thing)
elements[i] += j;
}
}
return score;
}
}
private boolean NimHelp(int[] elements) {
boolean[] isEmpty = new boolean[elements.length];
for (int i = 0; i < elements.length; i++) {
if (elements[i] == 0) {
isEmpty[i] = true;
} else {
isEmpty[i] = false;
}
}
for (boolean value : isEmpty) {
// If not all value is empty return false
if (!value)
return false;
}
return true;
}
public void NimResult(int player,int result)
{
if (player == 1) {
result = NimSolver(true);
} else if (player == 2) {
result = NimSolver(false);
}
if (result == 1) {
System.out.println("");
System.out.println("PLAYER 1 WON");
} else {
System.out.println("");
System.out.println("PLAYER 2 WON");
}
}
public void NimPrint(ArrayList<Integer> element)
{
System.out.println("");
System.out.print("MATCHES--------------------------------------");
for(int i = 0; i < element.size() ;i++)
{
System.out.println("");
for (int j = 0; j < element.get(i) ; j++) {
System.out.print("|");
}
}
}
}
Here is the code for Test Main class:
package Main;
import java.util.ArrayList;
import java.util.Scanner;
import Nim.NimGame;
public class Main {
public static void main(String[] args) {
int rows;
int elementTmp;
ArrayList<Integer> rowTmp = new ArrayList<Integer>();
int playerNo;
int result = 0;
int[] elements;
#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.print("Input number of rows: ");
rows = sc.nextInt();
elements = new int[rows];
System.out.println("");
System.out.println("Input number of elements in each row");
for (int i = 0; i < rows; i++) {
System.out.print("Row number " + (i + 1) + " : ");
elementTmp = sc.nextInt();
elements[i] = elementTmp;
rowTmp.add(elementTmp);
}
NimGame nim = new NimGame(elements);
nim.NimPrint(rowTmp);
System.out.println("");
System.out.println("---------------------------------------------");
System.out.println("");
System.out.println("First player to move");
System.out.println("1) Player 1");
System.out.println("2) Player 2");
System.out.print("Input: ");
playerNo = sc.nextInt();
nim.NimResult(playerNo, result);
}
}
It works for the sequence: 3 rows , Row1 = 1, Row2 = 2, Row3 = 3 for example:
Input number of rows: 3
Input number of elements in each row
Row number 1 : 1
Row number 2 : 2
Row number 3 : 3
MATCHES--------------------------------------
|
||
|||
---------------------------------------------
First player to move
1) Player 1
2) Player 2
Input: 1
PLAYER 2 WON
But it doesn't work for all the sequences. I don't understand why.
I'm working on a google challenge, and I have to solve a puzzle. For this puzzle I have to test if any number touching it on any four sides are equal to one. If so I must change the to the opposite. If one then zero. If zero the one. When I try to run the following code the code lab I'm trying to run it on says the following "Code Timed Out". I checked it, d it does not seem like the loop should be infinite. No matter what it should eventually return -1 or the number of steps. Can anyone explain this.
import java.util.Arrays;
public class FooReal {
public static boolean[] elementsOn = {false, false};
public static void main(String args[]) {
int[][] grid = {{1, 1}, {0, 0,}};
System.out.println(answer(grid));
}
public static int answer(int[][] grid) {
int steps = 0;
while (containsOn(grid)) {
for (int index = 0; index < grid.length; index++) {
for (int subIndex = 0; subIndex < grid[index].length; subIndex++) {
if (grid[index][subIndex] == 1) {
elementsOn = isElementOn(grid, new int[] {index, subIndex});
if (elementsOn[0] || elementsOn[1]) {
steps++;
for (int counter = 0; counter < grid.length; counter++) {
if (grid[counter][subIndex] == 1) {
grid[counter][subIndex] = 0;
} else {
grid[counter][subIndex] = 1;
}
}
for (int counterTwo = 0; counterTwo < grid[index].length; counterTwo++) {
if (grid[index][counterTwo] == 1) {
grid[index][counterTwo] = 0;
} else {
grid[index][counterTwo] = 1;
}
}
if (grid[index][subIndex] == 1) {
grid[index][subIndex] = 0;
} else {
grid[index][subIndex] = 1;
}
}
}
}
if (steps > 15) {
steps = -1;
return steps;
}
}
}
return steps;
}
public static boolean[] isElementOn(int[][] grid, int[] elements) {
boolean[] elementsOn = {false, false};
//Check if any are on in x row.
try {
if (grid[elements[0] + 1][elements[1]] == 1) {
elementsOn[0] = true;
}
} catch (ArrayIndexOutOfBoundsException e) {}
try {
if (grid[elements[0] - 1][elements[1]] == 1) {
elementsOn[0] = true;
}
} catch (ArrayIndexOutOfBoundsException e) {}
//Check if any are on in y row.
try {
if (grid[elements[0]][elements[1] + 1] == 1) {
elementsOn[1] = true;
}
} catch (ArrayIndexOutOfBoundsException e) {}
try {
if (grid[elements[0]][elements[1] - 1] == 1) {
elementsOn[1] = true;
}
} catch (ArrayIndexOutOfBoundsException e) {}
return elementsOn;
}
public static boolean containsOn(int[][] grid) {
for (int index = 0; index < grid.length; index++) {
for (int subIndex = 0; subIndex < grid[index].length; subIndex++) {
if (grid[index][subIndex] == 1) {
return true;
}
}
} return false;
}
}
I have to make a program that converts Roman numbers to decimal. I am confused about how to write the conditions for the Roman numbers, such as IV (4), IX (9), XL (40) and CM(900). The code that I wrote works for all the other numbers.
public static void main(String[] args) {
System.out.print("Enter a roman numeral: ");
Scanner in = new Scanner(System.in);
String Roman = in.next();
int largo = Roman.length();
char Roman2[] = new char[largo];
int Roman3[] = new int[largo];
for (int i = 0; i < largo; i++) {
Roman2[i] = Roman.charAt(i);
}
for (int i = 0; i < largo; i++) {
if (Roman2[i] == 'I') {
Roman3[i] = 1;
} else if (Roman2[i] == 'V') {
Roman3[i] = 5;
} else if (Roman2[i] == 'X') {
Roman3[i] = 10;
} else if (Roman2[i] == 'L') {
Roman3[i] = 50;
} else if (Roman2[i] == 'C') {
Roman3[i] = 100;
} else if (Roman2[i] == 'M') {
Roman3[i] = 1000;
}
}
int total = 0;
for (int m = 0; m < Roman3.length; m++) {
total += Roman3[m];
}
System.out.println("The Roman is equal to " + total);
}
You can check the previous digit.
For example, I added the condition that detects IV :
if (Roman2[i]=='I'){
Roman3[i]=1;
} else if (Roman2[i]=='V'){
Roman3[i]=5;
if (i>0 && Roman2[i-1]=='I') { // check for IV
Roman3[i]=4;
Roman3[i-1]=0;
}
} else if (Roman2[i]=='X'){
Roman3[i]=10;
} else if (Roman2[i]=='L'){
Roman3[i]=50;
} else if (Roman2[i]=='C'){
Roman3[i]=100;
} else if (Roman2[i]=='M'){
Roman3[i]=1000;
}
Define enum like below:
public enum RomanSymbol {
I(1), V(5), X(10), L(50), C(100), D(500), M(1000);
private final int value;
private RomanSymbol(final int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
public int calculateIntEquivalent(final int lastArabicNumber, final int totalArabicResult) {
if (lastArabicNumber > this.value) {
return totalArabicResult - this.value;
} else {
return totalArabicResult + this.value;
}
}
}
And use it like RomanSymbol.I.getValue() which will return 1 and similarly for other.
So if you accept character from user, you can get the values as:
char symbol = 'I';//lets assume this is what user has entered.
RomanSymbol rSymbol = RomanSymbol.valueOf(String.valueOf(symbol));
int invalue = rSymbol.getValue();
And if you have string like IV, then you could calculate on something like for example:
int lastValue = rSymbol.calculateIntEquivalent(intValue, 0);
lastValue = rSymbol.calculateIntEquivalent(intValue, lastValue); //and so on