Array: Deck of cards

Question: Write a program that will pick four random cards from a deck of cards

Examples:

Output 1:

9 of Hearts
6 of Spade
4 of Diamond
2 of Spade

Output 2:

2 of Hearts
Queen of Spade
4 of Clubs
5 of Hearts

package Array;

/**
 * Created by aarushi on 30/4/21.
 * Q: Create a program that will randomly select four cards from a deck of cards.
 */

public class ArrayDeckOfCards {

    /*Step 1: Create an array of 52 cards
      Step 2: Initialize the array with values 0-51
      (Formula: 0-12, 13-26, 27-40, 41-52 are Spades, Hearts, Diamonds, and Clubs respectively.
       Between the four types of cards, we can randomly select one by cardnumber%13 and
       select between 1-13 by using cardnumber%13)
       Step 3: Shuffle the cards
       Step 4: Display the top four cards
     */

    public static void main (String [] args){
        //create an array of 52 cards
        int [] deck = new int [52];
        String [] cardTye= {"Spade", "Hearts", "Diamond", "Clubs"};
        String [] cardNumber = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};

        //Initializing the array with values 0-51
        for(int i=0; i<deck.length; i++){
            deck[i]=i;
        }

        //method 1 for solving the problem
        //shuffle cards and apply formula
        for (int i = 0; i < 4; i++) {
            int randNumber = (int)(Math.random() * deck.length);
            String suit = cardTye[randNumber / 13];
            String rank = cardNumber[randNumber % 13];
            System.out.println(rank + " of " + suit);
        }

        //method 2 of solving the same problem
        //shuffling cards
        for (int i=0; i<deck.length; i++){
            int randNum= (int) (Math.random()*deck.length);
            int temp= deck[i];
            deck[i]=deck[randNum];
            deck[randNum]= temp;
        }

        for (int i=0; i<4; i++){
            System.out.println(cardTye[deck[i]/13] + " " + cardNumber[deck[i]%13]);
        }
    }

}

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: