This is not a duplicate. I understand how easy this is if you can sort, but I am not allowed to use the sort method for arrays and I am not allowed to write my own. I can't find any help with this anywhere, including StackOverflow.
In this scenario, I have a method that is supposed to check whether or not a five card hand is a straight. I have a card object that holds a value (integer) and a suit (integer). I also have some rules about implementing this method.
That last rule is what is killing me. I have an array of cards. If I could just sort it, this would be so easy but I can't even write my own method to sort the array. For my other methods it simple to iterate through the hand and store the information about the hand in two separate arrays like this:
private static int[] cardValues = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
private static int[] cardSuits = {0, 0, 0, 0, 0};
private static void evaluationHelper(Card[] cards) {
for (int i = 0; i < cardValues.length; i++) {
cardValues[i] = 0;
}
for (int i = 0; i <cardSuits.length; i++) {
cardSuits[i] = 0;
}
for (int i = 0; i < 5; i++) {
cardValues[cards[i].getValue() - 1]++;
cardSuits[cards[i].getSuit()]++;
if (cards[i].getValue() == 1) {
cardValues[9]++;
}
}
}
So in my first attempt to solve this issue I tried something like this:
public static boolean hasStraight(Card [] cards) {
int sequenCounter = 0;
evaluationHelper(cards);
for (int i = 0; i < cardValues.length; i++) {
if (sequenCounter != 5) {
if (cardValues[i] != 0) {
sequenCounter++;
} else {
sequenCounter = 0;
}
} else {
return true;
}
}
return false;
}
That didn't work. So then I tried this:
public static boolean hasStraight(Card [] cards) {
int min = 100, max = 0;
boolean seenSix = false, seenAce = false;
evaluationHelper(cards);
for (int i = 0; i < cards.length; i++) {
if (cards[i].getValue() > max) {
max = cards[i].getValue();
}
if (cards[i].getValue() < min) {
min = cards[i].getValue();
}
if (cards[i].getValue() == 6) {
seenSix = true;
}
if (cards[i].getValue() == 1) {
seenAce = true;
}
}
if (seenSix && seenAce) {
max = 10;
}
if (max - min == 4) {
return true;
}
return false;
}
That doesn't work either. I'm getting frustrated as both of these attempts went through many different changes over the course of overs and nothing has worked. I can't even figure out why they aren't working. The only information I have is that this method isn't spitting out the correct value. I don't know what values are being passed to the method. I don't know what the method is spitting out during the test. It could be spitting out false when it's supposed to be spitting true or vice versa. Please help!
In your evaluationHelper
you forgot to address when an ace is 10
adding:
if (cards[i].getValue() == 10) {
cardValues[0]++;
}
will make at least your first solution work (I haven't checked the second).
Note that what this method does is still a form of Radix sort so I'm not sure if it satisfies your requirement.