468,765 Members | 1,001 Online

# random number picker code ??

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.
May 22 '06 #1
5 1540
> 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.

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
May 22 '06 #2
"Milsnips" <mi******@hotmail.com>'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)

--
People are like tea bags.
You have to put them in hot water before you know how strong they are. (Bill Rayburn)

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

return nm;
}

Regards,
Tasos

May 22 '06 #4
> int[] GetNums(int[] nums, int numToReturn)
{
int[] nm = new int[numToReturn];
if (nums.Length <= numToReturn)
{
for (int i=0;i<nums.Length;i++)
{
nm[i] = nums[i];
}
}
else
{
Random rnd = new Random(123);
for (int i=0;i<numToReturn;i++)
{
int idx = rnd.Next() % nums.Length;
nm[i] = 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
May 22 '06 #5
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

May 22 '06 #6

### This discussion thread is closed

Replies have been disabled for this discussion.