7

I am having a tough time trying to create a "shuffleDeck()" method.

What I am trying to do is create a method that will take an array parameter (which will be the deck of cards) shuffle the cards, and return the shuffled array list.

This is the code:

class Card
{
    int value;
    String suit;
    String name;

    public String toString()
    {
        return (name + " of " + suit);
    }
}

public class PickACard
{
    public static void main( String[] args)
    {   
        Card[] deck = buildDeck();
        // display Deck(deck); 

        int chosen = (int)(Math.random()* deck.length);
        Card picked = deck[chosen];

        System.out.println("You picked a " + picked + " out of the deck.");
        System.out.println("In Blackjack your card is worth " + picked.value + " points.");

    }

    public static Card[] buildDeck()
    {
        String[] suits = {"clubs", "diamonds", "hearts", "spades" };
        String[] names = {"ZERO", "ONE", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "Jack", "Queen", "King", "Ace" };

        int i = 0;
        Card[] deck = new Card[52];

        for ( String s: suits )
        {   
            for ( int v = 2; v<=14; v++)
            {
                Card c = new Card();
                c.suit = s;
                c.name = names[v];
                if ( v == 14)
                    c.value = 11;
                else if ( v>10)
                    c.value = 10;
                else
                    c.value = v; 

                deck[i] = c;
                i++;
            }
        }
        return deck; 
    }

    public static String[] shuffleDeck( Card[] deck) 
    {
        /** I have attempted to get two index numbers, and swap them. 
        I tried to figure out how to loop this so it kind of simulates "shuffling". 
        */
    }

    public static void displayDeck( Card[] deck)
    {
        for ( Card c: deck) 
        {   
            System.out.println(c.value + "\t" + c);
        }
    }
}
Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353
user2690972
  • 131
  • 1
  • 1
  • 12
  • 4
    Convert the array to a `List` and call `Collections.shuffle(list)`. – Sotirios Delimanolis Aug 27 '13 at 15:47
  • 1
    The code you posted is meaningless because it's missing the most important part - your attempted shuffle implementation. I've voted to close as you've not appeared to have attempted this at all. – Duncan Jones Aug 27 '13 at 15:49
  • If you don't want to create a `List`, I suppose another alternative would be to use `Arrays#sort(T[], Comparator)` except randomly return -1 and 1. – Josh M Aug 27 '13 at 15:52
  • btw, use enums instead array of strings, if you do it, you can simplified build deck method – user902383 Aug 27 '13 at 16:02

4 Answers4

11

How about:

List<Card> list =  Arrays.asList(deck);
Collections.shuffle(list);

Or one-liner:

Collections.shuffle(Arrays.asList(deck));
Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135
rocketboy
  • 9,573
  • 2
  • 34
  • 36
  • What about the `Card[]`? – Josh M Aug 27 '13 at 15:51
  • 2
    But you missed your result in one-liner: which variable contains shuffled content? ;) – Radio Rogal Mar 09 '17 at 16:07
  • 1
    I was wrong: Arrays.asList creates an array-based list so when Collections swap any elements in this list it the same as it swap them in array. – Radio Rogal Mar 09 '17 at 16:16
  • 1
    @khelwood Oops.. you're completely right. In my test case I've accidentally used `int`. In OP's code he uses `Card`, so then it indeed works. I've rolled back the one-liner (with fixed typo), and will delete my comment above. (And yes, I indeed know that `Arrays.asList(int[])` results in `List`. :) ) – Kevin Cruijssen Jul 10 '19 at 20:09
3

One way is to convert the array to a list, and use java.util.Collections.shuffle(array) to shuffle it:

Card[] deck = ...;
List<Card> list = Arrays.asList(deck);
Collections.shuffle(list);

If you do still need an array instead of a List, you can add:

list.toArray(deck);

Here is a TIO (Try-it-online) link to see the array to list conversion and shuffling in action.

Code of the TIO copied below as reference:

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

class M{
  public static void main(String[] a){
    // Original array
    Integer[] array = new Integer[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    System.out.println("before: " + Arrays.toString(array));

    // Convert array to list
    List<Integer> list = Arrays.asList(array);
    // And shuffle that list
    Collections.shuffle(list);
    System.out.println("after as list: " + list);

    // (Optional) then convert the list back to an array,
    // and save it in its initial variable (`array` in this case)
    list.toArray(array);
    System.out.println("after as array: " + Arrays.toString(array));
  }
}
Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135
  • 1
    You don't have to do `list.toArray(deck);`. After running `Collections.shuffle(list);`, `deck` has already been shuffled. This is because `Arrays.asList()` returns a list as a view of the array. –  Mar 27 '21 at 22:31
0

I see two ways to do it:

-> You can use a shuffle algorithm like the Fisher-Yates shuffle algorithm if you want to implement yourself the method.

-> You can use the shuffle method from Collections

Julien
  • 2,256
  • 3
  • 26
  • 31
0

If this is for a school project (as I think it is), you might not be allowed to use built-in functions such as Collections::shuffle(). If this is the case, then you must try to simulate randomness (which in programming can be surprisingly hard).

The most common way to create a sense of randomness is to use an RNG (random number generator). As you said

I have attempted to get two index numbers, and swap them.

Correct. One way to shuffle is to pick one card at a time and randomly select another card to swap the position with.

  • You know the deck always has 52 cards.
  • You have a random generator to select a random index.
  • You have a programming language with loop-structures.

With these tools you can implement your own shuffle-function quite easily.

supertopi
  • 3,469
  • 26
  • 38