[Tfug] random squares

Robert Hunter hunter at tfug.org
Sun Oct 21 13:13:57 MST 2007


On 10/21/07, christopher floess <skeptikos at gmail.com> wrote:
> Hi, everyone. I have to write a program in java that
> involves a 2d array as a game board. Given a number
> in the constructor, I have to assign that many squares
> to be 'mines'. I know I could use math.random(), but
> would anyone recommend a better way to do this?

What you want is a sequence of random but unique numbers in a given
range.  This is similar to dealing a hand from a deck of cards.  First
you shuffle the cards, and then you pick, for example, 5 cards off the
top of the deck.  This is especially nice if a "shuffle" function is
already provided for you.  I know that C++ STL provides a shuffle
algorithm, and it seems that there is one in Java, as well.  Hope that
helps...

http://en.wikipedia.org/wiki/Shuffle


-- 
Rob




More information about the tfug mailing list