El algoritmo es bastante sencillo.
- Ordenas el arreglo para tener todas tus cartas en orden (da igual si es ascendente o descendente)
- Filtras todos aquellos que tengan el mismo valor que tu segunda carta (A, 2, ..., Q, K)
- Si el número de elementos filtrados es diferente a 4, significa que no tienes póker
¿Por qué se compara con la segunda carta?
En realidad se podría comparar con la segunda, tercera o cuarta carta, dado que para un póker existen dos escenarios:
- Al ser ordenadas, las primeras 4 cartas son del mismo número
- Al ser ordenadas, las últimas 4 cartas son del mismo número
En código Java.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// Poker of J
System.out.println(hasPoker("JD", "JT", "JP", "JC", "9D"));
// Poker of nines
System.out.println(hasPoker("9D", "9T", "9P", "9C", "4D"));
// NOT Poker
System.out.println(hasPoker("9D", "7T", "9P", "4C", "4D"));
}
/**
* This method is used to know if the player's hand is poker
* @param hand carts in hand
* @return returns true if the hand is poker, false otherwise
* @throws IllegalArgumentException If the number of cards in hand differs from 5
*/
private static boolean hasPoker(String... hand) {
if(hand.length != 5) {
throw new IllegalArgumentException("Expected 5 cards, got " + hand.length);
}
Arrays.sort(hand);
// Este substring lo que hace es quitar el palo dejando únicamente el número de la carta (A, 2, ..., 10, ..., K)
String poker = hand[2].substring(0, hand[2].length() - 1);
return Arrays.stream(hand).filter(el -> el.startsWith(poker)).count() == 4;
}
}
Explicación del código
- Se declara un método que recibe una mano (
private static boolean hasPoker(String... hand)
)
- Como verás recibe un argumento de "n" variables tipo String (
String...
), por ello mismo debemos de arrojar una excepción si la mano es inválida
if(hand.length != 5) {
throw new IllegalArgumentException("Expected 5 cards, got " + hand.length);
}
- Se ordenan los elementos recibidos con el método
Arrays.sort
- Se filtran los elementos cuya primera letra sea igual a la primera letra del segundo elemento con ayuda de
Streams.filter()
- Se cuentan el número de elementos que sobraron con
Streams.count()
- Se devuelve verdadero si el conteo es igual a 4, falso de lo contrario
Resultados de la ejecución
true
true
false
EDIT
Se propone una segunda solución evitando temas más avanzados como los Streams o los varargs
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// Poker of J
System.out.println(hasPoker2(new String[]{"JD", "JT", "JP", "JC", "9D"}));
// Poker of nines
System.out.println(hasPoker2(new String[]{"9D", "9T", "9P", "9C", "4D"}));
// NOT Poker
System.out.println(hasPoker2(new String[]{"9D", "7T", "9P", "4C", "4D"}));
}
/**
* This method is used to know if the player's hand is poker
* @param hand carts in hand
* @return returns true if the hand is poker, false otherwise
* @throws IllegalArgumentException If the number of cards in hand differs from 5
*/
private static boolean hasPoker2(String[] hand) {
if(hand.length != 5) {
throw new IllegalArgumentException("Expected 5 cards, got " + hand.length);
}
Arrays.sort(hand);
if (hand[0].substring(0, hand[0].length() - 1).equals(hand[3].substring(0, hand[3].length() - 1)))
return true;
return hand[1].substring(0, hand[1].length() - 1).equals(hand[4].substring(0, hand[4].length() - 1));
}
}
Nota:
Como se puede observar, se evalúan los dos casos mencionados en la respuesta a ¿Por qué se compara con la segunda carta? en estas líneas
if (hand[0].substring(0, hand[0].length() - 1).equals(hand[3].substring(0, hand[3].length() - 1)))
return true;
return hand[1].substring(0, hand[1].length() - 1).equals(hand[4].substring(0, hand[4].length() - 1));
EDIT 2
De igual manera se pueden proponer soluciones que no necesiten ordenamiento como las siguientes:
// Se necesita hacer el import de java.util.ArrayList
/**
* This method is used to know if the player's hand is poker
* @param hand carts in hand
* @return returns true if the hand is poker, false otherwise
* @throws IllegalArgumentException If the number of cards in hand differs from 5
*/
private static boolean hasPoker3(String[] hand) {
if(hand.length != 5) {
throw new IllegalArgumentException("Expected 5 cards, got " + hand.length);
}
ArrayList<String> set = new ArrayList<>(5);
for (String card : hand) {
if (!set.contains(card.substring(0, card.length() - 1)))
set.add(card.substring(0, card.length() - 1));
}
return set.size() == 2;
}
/**
* This method is used to know if the player's hand is poker
* @param hand carts in hand
* @return returns true if the hand is poker, false otherwise
* @throws IllegalArgumentException If the number of cards in hand differs from 5
*/
private static boolean hasPoker4(String[] hand) {
if(hand.length != 5) {
throw new IllegalArgumentException("Expected 5 cards, got " + hand.length);
}
HashSet<String> set = new HashSet<>(5);
for (String card : hand) {
set.add(card.substring(0, card.length() - 1));
}
return set.size() == 2;
}
Donde se implementa un HashSet o tratando de imitar su comportamiento un ArrayList, los cuales guardan sin repetición los valores de los números que tienes en tu mano. Si tienes sólo 2 números distintos en tu mano, significa que tienes póker, de lo contrario no.