Avatar billede di8leva Nybegynder
14. marts 2005 - 14:06 Der er 4 kommentarer og
1 løsning

Shuffling cards

I have a Vector with 52 objects of type "Card" (which consist of an int (value) and a String (color)).

I need some kind of method to "shuffle" the cards, or randomize the order of them.

As of now, I use:

Collections.sort(_cards, _shuffler);

where _shuffler is a Comparator looking like this:

public int compare(Object o1, Object o2)
{
    return (int)((Math.random() - 0.5) * 100);
}

Can you see any drawbacks with my shuffling method? Can you think of a better one. More accurate, or perhaps faster?

Answer in danish, swedish or english :)
Avatar billede fgsupermand Nybegynder
14. marts 2005 - 14:39 #1
I suggest you use the java.util.Random class instead of Math.random(), read why here:
http://java.sun.com/developer/JDCTechTips/2001/tt0925.html
Avatar billede fgsupermand Nybegynder
14. marts 2005 - 14:42 #2
Ohh I forgot:
The method "nextInt(n)" in the class: java.util.Random is faster then Math.random() because it uses integers and not floating point.
Avatar billede arne_v Ekspert
14. marts 2005 - 14:44 #3
Why not:

Collections.shuffle(_cards);

?
Avatar billede di8leva Nybegynder
14. marts 2005 - 16:07 #4
arne_v >> hehe, maybe I should have read more. Just what I am looking for, and way faster than my own algorhitm.

To be sure that if was shuffled, I ran my "Collections.sort(...)" ten times. Do you think I need to do that with "Collections.shuffle()" ?

And feel free to place an answer :)

Also thanks to fgsupermand for telling me about nextInt(), although I will not use this implementation more
Avatar billede arne_v Ekspert
14. marts 2005 - 16:35 #5
answer

no once should be enough (probably also with the sort and random)
Avatar billede Ny bruger Nybegynder

Din løsning...

Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.

Loading billede Opret Preview
Kategori
Kurser inden for grundlæggende programmering

Log ind eller opret profil

Hov!

For at kunne deltage på Computerworld Eksperten skal du være logget ind.

Det er heldigvis nemt at oprette en bruger: Det tager to minutter og du kan vælge at bruge enten e-mail, Facebook eller Google som login.

Du kan også logge ind via nedenstående tjenester