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 14 of 14

Thread: shuffle array items?

  1. #1
    Junior Member
    Join Date
    Oct 2013
    Posts
    13
    Thanks
    6
    Thanked 1 Time in 1 Post

    Default shuffle array items?

    Hi guys, so I have the following piece of code:

     
    public class Test{
     
         public static void main (String args[]){
             int[] myList = {1,2,3,4,5};
             for (int i = 0; i < myList.length; i++) {
     
    	      System.out.println(myList[i] +" before");
     
                  int index = (int) (Math.random()* myList.length);
     
                  int temp = myList[i]; 
                  myList[i] = myList[index];
                  myList[index] = temp;
     
                  System.out.println(myList[i] +"after swap");
                }
         }
    }

    I have seen this from a Java book which says this is one way to shuffle the items in a given array. I don't believe it works though as I have tried it for myself and the Math.random() method is basically changing the values of the array cells and at the end I get a new array, say: {2,3,4,5,3}

    Can somebody tell me some good way of shuffling array items? I am still quite new to programming so would appreciate some simple answer! (if possible )


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: shuffle array items?

    Take a look at the doc for the shuffle() method in the Collections class. It describes the technique it uses.
    If you don't understand my answer, don't ignore it, ask a question.

  3. The Following User Says Thank You to Norm For This Useful Post:

    kassavetova (November 11th, 2013)

  4. #3
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: shuffle array items?

    The output you are seeing is the value that gets shuffled/swapped/moved because you have it inside the for loop. Try printing out each item of the array outside the loop. Either with another loop or use Arrays.toString()
    Improving the world one idiot at a time!

  5. The Following User Says Thank You to Junky For This Useful Post:

    kassavetova (November 11th, 2013)

  6. #4
    Member
    Join Date
    Oct 2013
    Location
    Saint-Petersburg, Russia
    Posts
    33
    Thanks
    0
    Thanked 5 Times in 5 Posts

    Default Re: shuffle array items?

    Few days ago I added explanation of simple shuffling algorithm to my site and dedicated task on it:

    Cards Shuffling - CodeAbbey

    Here it is proposed to be used on the deck of cards (which could be useful for some game etc.)

    Hope this explanation is simple enough...

  7. The Following User Says Thank You to rodiongork For This Useful Post:

    kassavetova (November 11th, 2013)

  8. #5
    Junior Member
    Join Date
    Oct 2013
    Posts
    13
    Thanks
    6
    Thanked 1 Time in 1 Post

    Default Re: shuffle array items?

    Thanks Junky, used another loop outside the first one and it worked.
    @Norm, I looked at the doc material but I was a bit confused on how to actually use the shuffle method so I googled it and most of the examples looked like this:
    import java.util.ArrayList;
    import java.util.Collections;
     
    public class ShuffleElementsOfArrayListExample {
     
      public static void main(String[] args) {
     
        //create an ArrayList object
        ArrayList arrayList = new ArrayList();
     
        //Add elements to Arraylist
        arrayList.add("A");
        arrayList.add("B");
        arrayList.add("C");
        arrayList.add("D");
        arrayList.add("E");
     
        System.out.println("Before shuffling, ArrayList contains : " + arrayList);
     
        /*
          To shuffle elements of Java ArrayList use,
          static void shuffle(List list) method of Collections class.
        */
     
        Collections.shuffle(arrayList);
     
        System.out.println("After shuffling, ArrayList contains : " + arrayList);
     
      }
    }

    So I tried compiling and running it but I got the following error:

    Note: Test.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.

    Not entirely sure what this means, any ideas?

    Also I was wondering if you could (please) hint me another way of shuffling array items because the one above I just posted is good but not that efficient if I had, say 100 array elements and I wanted them to be initialised by the user at run-time, using a loop for example. I am quite happy to use this one if I manage to figure out why I'm getting that error but I just want to stay on the safe side, in case I had a lot of array elements!

  9. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: shuffle array items?

    confused on how to actually use the shuffle method
    I wasn't suggesting that you use the shuffle() method. You asked:
    good way of shuffling array items?
    The doc for shuffle() describes its technique for doing the shuffle. You could write code using its technique to do a shuffle.
    If you don't understand my answer, don't ignore it, ask a question.

  10. #7
    Junior Member
    Join Date
    Oct 2013
    Posts
    13
    Thanks
    6
    Thanked 1 Time in 1 Post

    Default Re: shuffle array items?

    Oh I see, okay. Any idea why I'm getting the error in the above example?

  11. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: shuffle array items?

    The compiler will give more information about the error if you use the -Xlint compiler option as it suggested.
    Here is the command line I use for compiling:
    D:\Java\jdk1.7.0.7\bin\javac.exe -cp . -Xlint SWTButtonRev2.java
    If you don't understand my answer, don't ignore it, ask a question.

  12. #9
    Junior Member
    Join Date
    Oct 2013
    Posts
    13
    Thanks
    6
    Thanked 1 Time in 1 Post

    Default Re: shuffle array items?

    Yep I tried this but I haven't really encountered warnings of this type. To be frank never really encountered warnings when compiling a program at all... I am quite new to java so I guess that's why. If it's not too much to ask, can I ask you to have a look at them and see if you know what they mean?

  13. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: shuffle array items?

    Try compiling the program with the -Xlint option. If you have questions about the messages, copy the full text of the messaged and paste it here with you questions.
    If you don't understand my answer, don't ignore it, ask a question.

  14. #11
    Junior Member
    Join Date
    Oct 2013
    Posts
    13
    Thanks
    6
    Thanked 1 Time in 1 Post

    Default Re: shuffle array items?

    Nevermind, I didn't know it would still run if I tried it so I don't really care about the warnings anymore, thanks.

  15. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: shuffle array items?

    Sometimes the warnings are very important.
    You need to figure out how to use the -Xlint option.
    If you don't understand my answer, don't ignore it, ask a question.

  16. #13
    Junior Member
    Join Date
    Oct 2013
    Posts
    13
    Thanks
    6
    Thanked 1 Time in 1 Post

    Default Re: shuffle array items?

    Not sure what you mean by using the -Xlint option. I compiled it with -Xlint and I looked at the warnings already which didn't really make sense to me because as I mentioned before I'm quite new to programming. I contacted my lecturer who was really helpful and explained that I am getting these warnings due to ArrayList now being a generic class and apparently the preferred way to do it would be using ArrayList<String> instead of ArrayList. This topic has not been introduced yet so of course I was not expected to know that. So yeah, this pretty much saved me some time. I suppose I will return to the warnings one day when I actually understand what they are trying to say.

  17. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: shuffle array items?

    If you have questions about the messages, copy them and paste here.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Card shuffle program
    By Grot in forum What's Wrong With My Code?
    Replies: 6
    Last Post: March 10th, 2013, 01:24 PM
  2. checking array list items!!! urgent help please
    By hacikho in forum Java Theory & Questions
    Replies: 1
    Last Post: December 14th, 2011, 04:28 PM
  3. How to get a sum value from items listed in array ?
    By makarov in forum Loops & Control Statements
    Replies: 0
    Last Post: January 6th, 2010, 06:11 PM
  4. [SOLVED] I am trying to shuffle up an array
    By rsala004 in forum Collections and Generics
    Replies: 3
    Last Post: July 18th, 2009, 03:31 PM
  5. Different operation on Array
    By jempot in forum Collections and Generics
    Replies: 4
    Last Post: January 27th, 2009, 06:07 AM