random number picker code ??

M

Milsnips

hi there,

i'm after a small function that is kindof like the lottery picker programs,
i pass it some numbers, say (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15) and i want
it to return me 3 random numbers, none being the same.

any help appreciated.
thanks,
Paul.
 
H

Hans Kesting

hi there,
i'm after a small function that is kindof like the lottery picker programs, i
pass it some numbers, say (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15) and i want it
to return me 3 random numbers, none being the same.

any help appreciated.
thanks,
Paul.

Start with an array of booleans, index (+1) = lottery number.
Initialize with "false".

Get a random number (see Random class), see if that position is still
"false". If not, get a new (random) number, else set to "true".
Repeat 3 times.

Print all indexes (+1) with a "true" value.


Hans Kesting
 
J

Jan Hyde

"Milsnips" <[email protected]>'s wild thoughts were
released on Thu, 18 May 2006 07:53:35 +0200 bearing the
following fruit:
hi there,

i'm after a small function that is kindof like the lottery picker programs,
i pass it some numbers, say (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15) and i want
it to return me 3 random numbers, none being the same.

any help appreciated.
thanks,
Paul.

I think what you actually want is a shuffling algorithm,
then you just pick the first three numbers.




Jan Hyde (VB MVP)
 
T

Tasos Vogiatzoglou

int[] GetNums(int[] nums, int numToReturn)
{
int[] nm = new int[numToReturn];
if (nums.Length <= numToReturn)
{
for (int i=0;i<nums.Length;i++)
{
nm = nums;
}
}
else
{
Random rnd = new Random(123);
for (int i=0;i<numToReturn;i++)
{
int idx = rnd.Next() % nums.Length;
nm = nums[idx];
}
}

return nm;
}

Regards,
Tasos
 
H

Hans Kesting

int[] GetNums(int[] nums, int numToReturn)
{
int[] nm = new int[numToReturn];
if (nums.Length <= numToReturn)
{
for (int i=0;i<nums.Length;i++)
{
nm = nums;
}
}
else
{
Random rnd = new Random(123);
for (int i=0;i<numToReturn;i++)
{
int idx = rnd.Next() % nums.Length;
nm = nums[idx];
}
}

return nm;
}

Regards,
Tasos


But how do you make sure a number is not chosen twice?
(what happens if "idx" is 6 for the second time? It will select
"nums[6]" for a second time)

Hans Kesting
 
T

Tasos Vogiatzoglou

He can iterrate through the table to check if the number is already
selected.

I'll post in a couple of minutes a revised sample :)

Tasos
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top