Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 13 of 13

Thread: Is there a card-shuffling Java class available?

  1. #1
    Junior Member
    Join Date
    Mar 2019
    Location
    Uji-shi, Kyoto-fu, Japan
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question Is there a card-shuffling Java class available?

    I'm working on a program to play through a particular variety of solitaire to determine whether or not a given shuffle of the cards can result in winning the game.

    Obviously, the first step is to create a deck (in this case, it's 2 decks for a total of 104 cards) and shuffle it.

    Since re-inventing the wheel is a mortal sin in the Church of Programming - plus the fact that I'd rather not spend the time to develop my own - I'm hoping that there
    is a Java class that someone, somewhere has already created that will accomplish this task.

    Does anyone know of such a class and where I might obtain it?

    Thanks in advance!

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,009
    Thanks
    52
    Thanked 2,365 Times in 2,319 Posts

    Default Re: Is there a card-shuffling Java class available?

    Yes, look at the Java SE API docs's Index of method names for ones starting with shuff
    https://docs.oracle.com/javase/8/docs/api/index.html
    Click on INDEX in the top blue banner, then click on S and search for shuffle for links to methods of interest
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Sep 2018
    Location
    Virginia
    Posts
    281
    My Mood
    Cool
    Thanks
    0
    Thanked 38 Times in 36 Posts

    Default Re: Is there a card-shuffling Java class available?

    Quote Originally Posted by BackInTheSaddle View Post

    Since re-inventing the wheel is a mortal sin in the Church of Programming - plus the fact that I'd rather not spend the time to develop
    my own - I'm hoping that there is a Java class that someone, somewhere has already created that will accomplish this task.
    Although a tongue-in-cheek statement, writing code that already exists is not necessarily a bad thing. It all depends on its complexity and how long it takes you to find the appropriate API. Even for those who never heard of the Fisher-Yates algorithm writing a pretty good shuffle routine would take only about 10 minutes.

    Regards,
    Jim

  4. #4
    Junior Member
    Join Date
    Mar 2019
    Location
    Uji-shi, Kyoto-fu, Japan
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Is there a card-shuffling Java class available?

    Quote Originally Posted by Norm View Post
    Yes, look at the Java SE API docs's Index of method names for ones starting with shuff
    https://docs.oracle.com/javase/8/docs/api/index.html
    Click on INDEX in the top blue banner, then click on S and search for shuffle for links to methods of interest
    Thank you very much! I'm a bit rusty (OK, more than a bit) and doing something this straightforward never occurred to me.

    I used the Collections.shuffle method in my card-playing program. To my astonishment, my shuffled deck now contains duplicate cards!

    I ran test code to display the contents of my ArrayList and it had 104 cards - 1 thru 13 each of Hearts, Diamonds, Clubs and Spades. Looking good!
    I then invoked the shuffle method and ran the test code again. It has many duplicates, with no discernible pattern. For the source of randomness, I did the
    new Random() thing.

    Would you know where I might find help with this?

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,009
    Thanks
    52
    Thanked 2,365 Times in 2,319 Posts

    Default Re: Is there a card-shuffling Java class available?

    my shuffled deck now contains duplicate cards!
    Can you make a small, simple program that compiles and executes and shows the problem and paste it here so we can see the problem?
    Be sure to wrap the code in code tags.
    If you don't understand my answer, don't ignore it, ask a question.

  6. #6
    Junior Member
    Join Date
    Mar 2019
    Location
    Uji-shi, Kyoto-fu, Japan
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Is there a card-shuffling Java class available?

    Quote Originally Posted by Norm View Post
    Can you make a small, simple program that compiles and executes and shows the problem and paste it here so we can see the problem?
    Be sure to wrap the code in code tags.
    I looked everywhere I could think of here on the Forum site, but couldn't find the definition of a code tag. (Sorry!)
    Can you give me an example of the valid format?

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,009
    Thanks
    52
    Thanked 2,365 Times in 2,319 Posts

    Default Re: Is there a card-shuffling Java class available?

    How to wrap your code with code tags:

    [code]
    **YOUR CODE GOES HERE**
    [/code]

    to get highlighting and preserve formatting.

    If you go to the Go Advanced page, the # near the end of the second row of buttons will wrap the selected text in code tags.
    If you don't understand my answer, don't ignore it, ask a question.

  8. #8
    Member
    Join Date
    Sep 2018
    Location
    Virginia
    Posts
    281
    My Mood
    Cool
    Thanks
    0
    Thanked 38 Times in 36 Posts

    Default Re: Is there a card-shuffling Java class available?

    Code tags are party of the BB Codes. When you go into the advanced editor (down and to the right of the normal editor box), you can see the BB codes at the end of the page. Here is a link to help. BB Code List - Java Programming Forums - The Java Community

    Regards,
    Jim

  9. #9
    Junior Member
    Join Date
    Mar 2019
    Location
    Uji-shi, Kyoto-fu, Japan
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Is there a card-shuffling Java class available?

    Quote Originally Posted by Norm View Post
    Can you make a small, simple program that compiles and executes and shows the problem and paste it here so we can see the problem?
    Be sure to wrap the code in code tags.
    Here it is, quick and dirty, unpolished and unsophisticated - but it does produce an ArrayList with duplicate entries!

    Here's a Fun Fact: When I used a single 'deck' the shuffled ArrayList contained no duplicates, but when I used two 'decks', the duplicates appeared.

    import java.util.ArrayList;
    import java.lang.StringBuilder;
    import java.util.Collections;
    import java.util.ListIterator;
    import java.util.Random;
     
    public class ProgramTester {
     
        public static void main(String[] args) {
            int rank = 0;
            char suit;
     
            StringBuilder sb = new StringBuilder();
     
            ArrayList<String> cardSuitandRank = new ArrayList();
            cardSuitandRank.ensureCapacity(104);
     
            // Create two decks of 52 cards each
            suit = 'H';
            for (int idx1 = 0; idx1 < 13; idx1++) {
     
                sb.append(suit);
                rank++;
                sb.append(rank);
                cardSuitandRank.add(sb.toString());
                sb.delete(0,sb.length());
     
            }
     
            rank = 0;
            suit = 'D';
            for (int idx1 = 0; idx1 < 13; idx1++) {
     
                sb.append(suit);
                rank++;
                sb.append(rank);
                cardSuitandRank.add(sb.toString());
                sb.delete(0,sb.length());
     
            }
     
            // Re-initialize rank for the second deck
            rank = 0;
            suit = 'S';
            for (int idx1 = 0; idx1 < 13; idx1++) {
     
                sb.append(suit);
                rank++;
                sb.append(rank);
                cardSuitandRank.add(sb.toString());
                sb.delete(0,sb.length());
            }
     
            rank = 0;
            suit = 'C';
            for (int idx1 = 0; idx1 < 13; idx1++) {
     
                sb.append(suit);
                rank++;
                sb.append(rank);
                cardSuitandRank.add(sb.toString());
                sb.delete(0,sb.length());
     
            }
            rank = 0;
            suit = 'H';
            for (int idx1 = 0; idx1 < 13; idx1++) {
     
                sb.append(suit);
                rank++;
                sb.append(rank);
                cardSuitandRank.add(sb.toString());
                sb.delete(0,sb.length());
     
            }
     
            rank = 0;
            suit = 'D';
            for (int idx1 = 0; idx1 < 13; idx1++) {
     
                sb.append(suit);
                rank++;
                sb.append(rank);
                cardSuitandRank.add(sb.toString());
                sb.delete(0,sb.length());
     
            }
     
            rank = 0;
            suit = 'S';
            for (int idx1 = 0; idx1 < 13; idx1++) {
     
                sb.append(suit);
                rank++;
                sb.append(rank);
                cardSuitandRank.add(sb.toString());
                sb.delete(0,sb.length());
            }
     
            rank = 0;
            suit = 'C';
            for (int idx1 = 0; idx1 < 13; idx1++) {
     
                sb.append(suit);
                rank++;
                sb.append(rank);
                cardSuitandRank.add(sb.toString());
                sb.delete(0,sb.length());
     
            }
            ListIterator iter = cardSuitandRank.listIterator();
            System.out.println("Prior to shuffle");
     
            do {
     
                System.out.println(iter.next());
     
            } while (iter.hasNext());
     
            Collections.shuffle(cardSuitandRank, new Random());
     
            ListIterator iter2 = cardSuitandRank.listIterator();
            System.out.println("After shuffle");
     
            do {
     
                System.out.println(iter2.next());
     
            } while (iter2.hasNext());
        }
     
    }
    Last edited by BackInTheSaddle; March 22nd, 2019 at 04:49 PM.

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,009
    Thanks
    52
    Thanked 2,365 Times in 2,319 Posts

    Default Re: Is there a card-shuffling Java class available?

    When I used a single 'deck' the shuffled ArrayList contained no duplicates, but when I used two 'decks', the duplicates appeared.
    That is what I would expect. Two decks would have 2 of each card. 2 Ace of Clubs, 2 King of Spades etc
    Please explain.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Mar 2019
    Location
    Uji-shi, Kyoto-fu, Japan
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Is there a card-shuffling Java class available?

    Quote Originally Posted by Norm View Post
    That is what I would expect. Two decks would have 2 of each card. 2 Ace of Clubs, 2 King of Spades etc
    Please explain.
    *Long_Sigh*

    As I approach my 70th birthday, I find myself doing things like this with increasing frequency. Not that they didn't occur when i was younger, but now it
    seems to happen more and more often.

    My apologies to everyone, especially to you, Norm, for wasting everyone's time with this idiocy.

    Baseball season is beginning here in Japan - watching the Hanshin Tigers lose on TV doesn't require any particular cognitive abilities...

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,009
    Thanks
    52
    Thanked 2,365 Times in 2,319 Posts

    Default Re: Is there a card-shuffling Java class available?

    Ok, good luck with the project. See you next time.

    There is a lot of repeated code in what you posted. Anything you repeat a block of code more than a couple of times, think about loops and arrays. Here is another solution:
            // Use array and loop to load 2 decks
            String[] suits = {"S", "H", "D", "C"};
            for(int deck=0; deck<2; deck++) {
               for(int suitIdx = 0; suitIdx < suits.length; suitIdx++) {
                  for (int rankC=1; rankC<=13; rankC++) {
                     cardSuitandRank.add(suits[suitIdx] + rankC);
                  }
               }
            }
            System.out.println(cardSuitandRank);
            // [S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, H1, H2, H3, H4, H5, H6, H7, H8, H9, H10, H11, H12, H13, 
            //  D1, D2, D3, D4, D5, D6, D7, D8, D9, D10, D11, D12, D13, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, 
            //  S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, H1, H2, H3, H4, H5, H6, H7, H8, H9, H10, H11, H12, H13, 
            //  D1, D2, D3, D4, D5, D6, D7, D8, D9, D10, D11, D12, D13, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13]
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Junior Member
    Join Date
    Mar 2019
    Location
    Uji-shi, Kyoto-fu, Japan
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Is there a card-shuffling Java class available?

    Quote Originally Posted by Norm View Post
    Ok, good luck with the project. See you next time.
    Just FYI - I'm a retired developer with decades of programming experience, including 15 years of programming in Java.

    My program has come a long way, although it's still not quite done, and - as one would expect with this type of project - it runs and runs and runs while the number of possible sequences of play expands geometrically (at least it's not exponentially!) and millions of possibilities have been explored with no end in sight. (Yes, I've tested for halting conditions!) I'm working on a standard iMac, and I worry about crashing the computer if its resources are insufficient to run the program to its conclusion. So far it hasn't seemed to have any trouble, but then I haven't let it run until the end yet. I set an arbitrary limit on the number of branches it will explore before stopping while displaying the state of the card tableaus (this is a solitaire-playing program looking for possible winning sequences).

    Once I'm satisfied that my logic will yield the correct results, I'm pondering the idea of rewriting it in some language that will compile to a nice, tight executable that will cough up the answer in less than a week (or however long it turns out that my Java program will need once I take off the limit). I'm sure that assembler would be lots of fun to learn and struggle with, there must be some other way that is somewhere in between. What would be your recommendation for a programming language I might use?

    I've done a bit of fiddling with Erlang, which is supposed to run very fast but is based on Lisp, which (so I hear) requires some odd brain wiring to understand well. Maybe you've used some language I've never heard of for tasks like this.
    Last edited by BackInTheSaddle; April 17th, 2019 at 04:10 PM.

Similar Threads

  1. Card Class (Setting string rank value. 1 = "Ace" etc)
    By ashboi in forum What's Wrong With My Code?
    Replies: 3
    Last Post: October 9th, 2012, 03:42 PM
  2. shuffling help
    By ronimacarroni in forum Algorithms & Recursion
    Replies: 9
    Last Post: April 15th, 2012, 11:23 PM
  3. [SOLVED] array not shuffling
    By captain in forum Collections and Generics
    Replies: 2
    Last Post: February 27th, 2012, 07:32 AM
  4. Shuffling a 2D array
    By Buzzins in forum Object Oriented Programming
    Replies: 6
    Last Post: January 16th, 2012, 12:47 PM
  5. CardGuesser. Stuck on Card class HELP!
    By Stormin in forum What's Wrong With My Code?
    Replies: 9
    Last Post: August 11th, 2010, 05:41 PM