jeudi 17 mars 2022

Returning collection of random elements from ArrayList using functional programming

Currently working on a card dealing project. I want a method that deals poker hands. It should randomly pick n(5) elements and return these in a collection(?). Also desired to use Random class to achieve randomness - school orders...

public ArrayList<PlayingCard> dealHand(int n){
        ArrayList<PlayingCard> hand = new ArrayList<>();
        Random random = new Random();
        for (int i = 0; i < n; i++) {
            PlayingCard card = this.deck.get(random.nextInt(this.deck.size()));
            if (!hand.contains(card)){
                hand.add(card);
            }
        }
        return hand;
    }

Assignment: "Create a "dealHand (int n)" method in the DeckOfCards class that randomly picks n cards from the deck and returns them in a collection. "N" is a number between 1 and 52 that is submitted as a parameter to the assign function. This feature can be used, for example, to draw n random cards from the deck. You again choose which class / interface from the Java library you use as the return type of the method."

How do I make this method fulfill the requirements mentioned earlier, using streams, filters and what not (functional programming and lambda)?

Thanks




Aucun commentaire:

Enregistrer un commentaire