Re: Shuffled Poker Deck
On Tue, 23 Jan 2007 17:12:39 -0000, Martin Krainer =
<NOSPAMmartin.krainer@inode.at> wrote:
Hi all,
Im new to Java, and as Training for me I tried to build an Application=
,
which returns a shuffled Pokerdeck. (Random from 1 to 52)
Maybe you will laugh, but i needed a whole day to solve it, and I thin=
k =
its
even not good solution.
Well, at least it works, but please could you give me a hint, how to =
solve
this problem easier.
Heres the code:
/**
* @(#)Poker.java
*
*
* @author Martin Krainer
* @version 1.00 2007/1/22
*/
public class Poker {
static int[] deck = new int[52];
void buildDeck() { // builds a deck with 52
(hopefully) different Integers
for (int i=0; i<52; i++) {
deck[i] = (int)(Math.random()*10E7);
}
}
void shuffledDeck(int[] a) { // now here I tried hard=
=
and
long to get a field with numbers from 1 to 52
long[] zahl= new long[52];
for (int i=0; i<10E7; i++) {
for (int j=0; j<52; j++) {
if (i == deck[j]) {
zahl[j] = j;
System.out.print( " " + (zahl[j]+1) );
}
}
}
}
public static void main(String[] args) {
Poker p = new Poker();
p.buildDeck();
p.shuffledDeck(deck); //well, it works, but.=
...
what do you think?
}
}
You only need to initialise your deck with the numbers between 0 and 51,=
=
you can do this without random numbers. Another option is to use an =
enumerated type to model the playing cards. Either way, all your =
buildDeck method needs to do is to ensure that each card is different, i=
t =
doesn't matter if they are all in order at this point, you will shuffle =
=
them later.
Don't use Math.random to generate random integers, use java.util.Random =
=
instead. Roedy Green has a decent discussion of generating random numbe=
rs =
in Java (here http://mindprod.com/jgloss/pseudorandom.html).
Which is more important to you here, the means or the end? If you just =
=
want to shuffle a deck as easily as possible, take a look at the shuffle=
=
method in the java.util.Collections class. If you want to write the =
shuffling routine yourself, search for the Fisher-Yates algorithm and tr=
y =
implementing that (I believe that the java.util.Collections shuffle meth=
od =
is an implementation of this algorithm). Alternatively, try the trivial=
=
algorithm used by PokerStars and described on their site =
(http://www.pokerstars.com/poker/room/features/security/).
Dan.
-- =
Daniel Dyer
https://watchmaker.dev.java.net - Evolutionary Algorithm Framework for J=
ava