How to organize (from highest to lowest) a hand of 5 deck-cards? or how to split an array of strings into sub arrays?

Viewed 31

I am stuck on how to organize 5 cards from highest to lowest. the 5 cards will come into the method as an array called handDeck, the array would look something like this: {"Ace spades", "Five hearts",...etc}. What I tried is iterate through the array and splitting each element into smaller array contain the first and second word for example: in the example array I wrote earlier, the first sub-array would look like this: {"Ace", "Spades"}. this can allow me to check every first element of those 5 sub-arrays and check which order they should follow. however, I don't know how to implement this sub-array method. i haven't coded in so long so my memory is very shady right now. also if you can give me a hint on how to check the order of the first element of the sub-arrays, that would be very helpful.

the code that I tried is this:

String[] deck = {"Ace spades", "Five hearts", "Four spades", "King diamonds", "Queen diamonds"};
for(int i = 0; i < 5; i++) {
   String s = deck[i];
   s.split(" ");
   System.out.println(s);
}
1 Answers

You need a way to compare string names with each other, so that you can determine "Jack" is ranked higher than "Ten" for example, but lower than "Queen". There are a number of ways to this, below is one.

As a first step, here is a map that will allow translating a card name to it's numeric position relative to the other card names. Ace is ranked the highest in position 13, while the Two card is ranked lowest in position 1.

static Map<String, Integer> positions = new HashMap<>();
static {
    positions.put("Two", 1);
    positions.put("Three", 2);
    positions.put("Four", 3);
    positions.put("Five", 4);
    positions.put("Six", 5);
    positions.put("Seven", 6);
    positions.put("Eight", 7);
    positions.put("Nine", 8);
    positions.put("Ten", 9);
    positions.put("Jack", 10);
    positions.put("Queen", 11);
    positions.put("King", 12);
    positions.put("Ace", 13);
}

Here's a simple usage below. All it's doing is calling Ararys.sort() with a compartor that looks up each card name in the positions map. Note that the "cards" array is just the card names and not card+suit like you posted (so "Ace", and not "Ace spades"):

public static void main(String[] args) {
    String[] cards = {
            "Ace",
            "Five",
            "Four",
            "King",
            "Queen"
    };

    System.out.println("before sort: " + Arrays.toString(cards));
    Arrays.sort(cards, Comparator.comparing(o -> positions.get(o)));
    System.out.println(" after sort: " + Arrays.toString(cards));
}

And here's the output from running that, first it prints the original array, then it prints the same array once more after the contents were sorted:

before sort: [Ace, Five, Four, King, Queen]
 after sort: [Four, Five, Queen, King, Ace]
Related