Sort LinkedList randomly java

2

I have a LinkedList of 104 elements and I need to sort them randomly in java.

It's a deck of cards and you have to shuffle before you start playing. I tried

for(int i =0;i<104;i++){
            int rand = (int) (Math.random() * 103) + 1;
            String q=mazo.get(rand);
            mazo.set(rand,mazo.get(i));
            mazo.set(rand,q);
        }
    
asked by Stivenson Sarrazola 30.03.2018 в 17:39
source

1 answer

0

You can do this with Collections.shuffle , which:

  

Randomly change the specified list using a source   default of randomness. All permutations occur with   approximately the same probability.

Code:

VIEW DEMO IN REXTESTER

We create a list with 10 elements and then make Collections.shuffle order it twice. You can see that each order is different from the original, and I distinguish between them:

    LinkedList<String> list = new LinkedList<String>();
    list.add("Elemento-01");
    list.add("Elemento-02");
    list.add("Elemento-03");
    list.add("Elemento-04");
    list.add("Elemento-05");
    list.add("Elemento-06");
    list.add("Elemento-07");
    list.add("Elemento-08");
    list.add("Elemento-09");
    list.add("Elemento-10");

    Collections.shuffle(list);
    System.out.println("1ª prueba:");
    for(String str: list){
        System.out.println(str);
    }

    Collections.shuffle(list);
    System.out.println("\n2ª prueba:");
    for(String str: list){
        System.out.println(str);
    }  

Exit:

1ª prueba:
Elemento-07
Elemento-02
Elemento-06
Elemento-08
Elemento-01
Elemento-10
Elemento-05
Elemento-03
Elemento-09
Elemento-04

2ª prueba:
Elemento-04
Elemento-06
Elemento-01
Elemento-08
Elemento-09
Elemento-07
Elemento-10
Elemento-02
Elemento-05
Elemento-03
    
answered by 30.03.2018 / 18:40
source