Generating Random Number Problem

Started by
0 comments, last by Tom Sloper 8 years, 9 months ago

Ok I am pulling my hair out on this one. I am trying to intialize an array size 52 with random numbers that represent a deck of cards.

A loop should count from 0-51 but it stops at various random values. I am using document.write to trouble shoot. As of now, calling the page

will generate a numbered list of random numbers. It should show 52 numbers but never does.

Here is the code. Help a guy out please? Thanks.

<html>
<head>

<script type="text/javascript" language="JavaScript">

function shuffle() {
//document.write("Got in shuffle" + "<br>");

var i;
var num; // Holds the generated random number
var card;
var deck_array = []; // 52 card deck
var dup_array = []; // This array used to track the generated number

//Don't know whether I need to initialize the arrays or not? But won't hurt.
for (i = 0; i < 52; i++) { dup_array = 0; deck_array = 0;}

//This loop is for initializing a 52 card deck
for (card = 0; card < 52; card++){

getRndNmbr:

num = Math.floor((Math.random() * 52) + 1);
document.write(card + " ");

// Check for duplicate numbers. Initially the dup_array should be all zeros.
// When a random number is generated, set that numbers dup location to “1” to indicate
// that this number was already generated and we need to generate another number.
// If this number was not generated before, set the dup location to “1” and set the
// deck_array current card location to the random number.

// If dup_array[num] is a "1", number was already picked, get another
if (dup_array[num] == 1) { getRndNmbr;}

// num was never generated. Set current location in the deck to num
// Populate the deck top to bottom
deck_array[card] = num;

document.write(deck_array[card] + " " + "<br>");

// Set the dup indicator so we don't pick the same number again
dup_array[num] = 1;

// document.write(dup_array[card] + " ");
// document.write(dup_array[num] + " ");
}

} // end shuffle

</script>
</head>

<body>
<script type="text/javascript" language="JavaScript">
shuffle();
</script>
</body>
</html>

Advertisement
Please don't cross-post. http://www.gamedev.net/topic/670018-new-game-programmer/

-- Tom Sloper -- sloperama.com

This topic is closed to new replies.

Advertisement