# Re: Generating a random number

Discussion in 'C++' started by Stewart Gordon, Jul 1, 2003.

1. ### Stewart GordonGuest

J. Campbell wrote:

<snip>
> RANDOMIZE TIMER
> CLS
> PRINT "This program prints a 4-digit random number with no repeting
> digits."
> PRINT "Well...the number isn't really random, since it is a subset"
> PRINT "of all the available 4-digit numbers."

By "available" do you mean "from the whole set of 4-digit numbers with
no repeating digits"? If so, I can't see any that it'll miss. Which
numbers are they?

> DO
> REDIM a(4) AS INTEGER '4-element array
> FOR i = 0 TO 4 STEP 1
>
> IF i = 0 THEN
> a(i) = 1 + (RND * 8) 'special case for first digit...make

Does the OP want a uniform distriution? Well, this doesn't even attempt
to produce one.

Should use

a(i) = INT(1 + RND*9)

and similarly with RND*10 for subsequent digits.

> ELSE
> nodup = false
> DO 'loop until a unique digit
> has been selected
> a(i) = RND * 9 'use 9, not 10 bec
> (0,1,2...8,9) has 10 elements
> FOR t = 0 TO i - 1 STEP 1
>
> IF a(i) <> a(t) THEN
> nodup = true 'Here "=" == "="

Why not initialise nodup = true just before the for loop rather than
setting it here?

> ELSE 'different from c++
> nodup = false
> EXIT FOR
> END IF
>
> NEXT t
> LOOP UNTIL nodup = true 'here "=" == "==" ;-)
> END IF
> NEXT i
>
> 'turn array into integer
> mynum = 0
> FOR i = 0 TO 3 STEP 1
> mynum = mynum + (1000 / (10 ^ i)) * a(i) 'this is to set the

<snip>

I guess slightly better would be something like

mynum = mynum + 10^(3-i) * a(i)

or even

FOR i = 3 TO 0 STEP -1
mynum = 10 * mynum + a(i)
NEXT i

Stewart.

--
My e-mail is valid but not my primary mailbox. Please keep replies on
on the 'group where everyone may benefit.

Stewart Gordon, Jul 1, 2003

2. ### J. CampbellGuest

Stewart Gordon <> wrote in message news:<bdscuq\$484\$>...
> J. Campbell wrote:
>
> <snip>
> > RANDOMIZE TIMER
> > CLS
> > PRINT "This program prints a 4-digit random number with no repeting
> > digits."
> > PRINT "Well...the number isn't really random, since it is a subset"
> > PRINT "of all the available 4-digit numbers."

>
> By "available" do you mean "from the whole set of 4-digit numbers with
> no repeating digits"? If so, I can't see any that it'll miss. Which
> numbers are they?
>

Hi Stuart. I was just trying to get the original poster headed in the
right direction. That was sloppy 5-min code. The point here was that
a randomly selected 4-digit number with no repeting digits is
different than a 4-digit random number. Thanks for the correction re
rnd...my code underrepresented the min and max value.

J. Campbell, Jul 2, 2003