Sort a deck of cards by suit, and then score

I have this Java class:

class Card { private Suit suit; private int rank; } 

( Suit listing)

There are four suits with a rank of 1–9 each and four suits with the only possible rank of 0. Each card exists in an unknown but constant number of copies among all cards. How would I sort the deck in the given order of costumes and increase the rank in each suit?

+4
source share
6 answers

Take a look at the Comparable implementation in the listing.

+2
source

You will need

  • implements the Comparable interface on a map object: add a compareTo function, which determines whether the other map should be before or after that one in sort order
  • implement a Comparator object that accepts two cards and indicates what order they should appear in

and then you can use Collections.sort on your list.

+3
source

Rename the Rank as well, and you can process the sorted deck as such:

  for (Suit suit : Suit.values()) for (Rank rank : Rank.values()) deck.add(new Card(rank, suit)); 
+2
source

Implement the implementation of the Comparable interface. You have only one method you need to write. Then they can be compared with each other, and you have a number of existing sorting options, such as static Arrays.sort , if you have an array or Collections.sort , if it's any type of Collection (List, Vector, etc.)

In addition to implementing on Card you may need to do the same for Suit , depending on how you do it.

+1
source

Here is an example of a map class. Since questions indicate that Kost will have a specific class, while the Rank will be an integer (in this example, I did not apply the rank check). Implementing the Comparable class allows the Card class to compare another card class. So the list / set of cards can be sorted.

 public class Card implements Comparable<Card>{ private SUIT cardSuit; private int cardRank; public enum SUIT {SPADE, CLUB, HEART, DIAMOND}; public Card(int cardRank, SUIT cardSuit) { this.cardSuit = cardSuit; this.cardRank = cardRank; } /** * Generates a random card */ public Card(){ this((int) (Math.random() * 9) , SUIT.values()[(int) (Math.random() * SUIT.values().length)]); } public String getSuit() { return cardSuit.toString(); } public int getRank() { return cardRank; } @Override public int compareTo(Card2 o) { if (this.cardRank == o.cardRank) { return this.cardSuit.compareTo(o.cardSuit); } else { return o.cardRank - this.cardRank; } } } 
0
source

A quick way to complete this task is Radix Sort . Set up an array of lists of card values, then go through your deck, placing each card in the appropriate list as it appears. Then merge all the lists together into a partially sorted deck. Now do the same, only with an array of costume lists. Combine all the lists together and you should have a sorted deck.

0
source

Source: https://habr.com/ru/post/1334969/


All Articles