Click here to Skip to main content
Click here to Skip to main content

How to generate many random various numbers?

By , 28 Jan 2011
 
1. We need an array of random various numbers between x[0] and x[n] like shuffling the cards.
 
For example: 8, 10, 5, 4, 7, 6, 3, 1, 9, 2 (between 1 and 10)
 
The following code is a method (with an overload) and generates an array of random various integer numbers:
 
//C#
public static int[] RandomNumbers(int min, int max)
{
    return RandomNumbers(min, max, 2);
}
public static int[] RandomNumbers(int min, int max, int derangement)
{
    if (min > max)
    {
        throw new Exception("The first parameter must be less (or equal) than the second.");
    }
    Random random = new Random();
    int count = max - min; ;
    int[] tempList = new int[count + 1];
    int counter = 0;
    for (int i = min; i <= max; i++)
    {
        tempList[counter] = i;
        counter++;
    }
 
    for (int i = 0; i < derangement; i++)
        for (int j = 0; j < count; j++)
        {
            int k = random.Next(0, count + 1);
            int l = random.Next(0, count + 1);
            if (k != l)
            {
		    //Swap TempList[k] with TempList[l]
                tempList[k] += tempList[l];
                tempList[l] = tempList[k] - tempList[l];
                tempList[k] = tempList[k] - tempList[l];
            }
        }
    return tempList;
}
 
Note: derangement is an integer variable to define the chance of the numbers derangement, but there is an inversely relationship between the performance and the value of the variable. The overload default is 2.
 
Now, It's ready to use the method:
 
//C#
int[] m = RandomNumbers(1, 56, 5);
foreach (int i in m)
{
    Console.Write("{0}, ",i);      
}
Console.ReadKey();
 
2. We need to generate a random number which has not been generated since runtime.
 
There has been a generated random number previously, but need to have a different one:

//C#
public static int RandomNumber(ref List<int> numbers, Random random)
{
    int count = numbers.Count;            
    int randomIndex = random.Next(0, count);
    int returnedNumber = numbers[randomIndex];
    numbers.RemoveAt(randomIndex);
    return returnedNumber;
}
 
It's requisite for using the method, to have a random variable and a list of numbers, for example:
 
//C#
Random random = new Random();
List<int> numbers = new List<int>();
for (int i = 0; i <= 1000; i++)
{
    numbers.Add(i);
}
 
//Ok, For each using the method, there is a new and defferent random number:

Console.WriteLine(RandomNumber(ref numbers, random));
Console.WriteLine(RandomNumber(ref numbers, random));
Console.WriteLine(RandomNumber(ref numbers, random));
Console.WriteLine(RandomNumber(ref numbers, random));
Console.WriteLine(RandomNumber(ref numbers, random));
Console.ReadKey();
 
The second approach has a better performance.
 
Good Luck!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Shahin Khorshidnia
Software Developer (Senior)
Iran (Islamic Republic Of) Iran (Islamic Republic Of)
Member
Microsoft Certified Technology Specialist (MCTS)
 

"شاهین خورشیدنیا"

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralRe: Because it gives you a uniform distribution (which your meth...memberHenry.Ayoola2 Sep '11 - 4:31 
Because it gives you a uniform distribution (which your method doesn't) and has better algorithmic complexity and minimal consumption of random bits.
GeneralReason for my vote of 5 Good tip.memberProEnggSoft24 Feb '12 - 21:03 
Reason for my vote of 5 Good tip.
GeneralRe: Thank you very much.memberShahin Khorshidnia25 Feb '12 - 3:39 
Thank you very much.
GeneralReason for my vote of 5 A genuine tip...Good work bro..memberPravin Patil, Mumbai13 Sep '11 - 0:29 
Reason for my vote of 5 A genuine tip...Good work bro..
GeneralRe: Thank you.memberShahin Khorshidnia14 Sep '11 - 21:35 
Thank you.
GeneralReason for my vote of 1 A better way of doing this has been ...memberHenry.Ayoola31 Aug '11 - 21:46 
Reason for my vote of 1 A better way of doing this has been known for a very long time: http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
GeneralRe: Thank you. And would you explain why that way is better?memberShahin Khorshidnia1 Sep '11 - 10:34 
Thank you. And would you explain why that way is better?
GeneralNice article...memberPradip_Bobhate31 Aug '11 - 4:52 
Nice article...
GeneralReason for my vote of 5 Usefull... Some people couldn't prob...memberToli Cuturicu13 Feb '11 - 11:44 
Reason for my vote of 5 Usefull... Some people couldn't probably do this.
GeneralRe: Thank you TolimemberShahin Khorshidnia14 Feb '11 - 0:15 
Thank you Toli
GeneralGood!!!membershakil030400331 Jan '11 - 22:10 
Good!!!
GeneralRe: Thank you shakilmemberShahin Khorshidnia1 Feb '11 - 23:30 
Thank you shakil
GeneralReason for my vote of 5 Good trick. thank youmemberArahs28 Jan '11 - 2:40 
Reason for my vote of 5 Good trick. thank you
GeneralRe: Thank you my friend.memberShahin Khorshidnia28 Jan '11 - 21:48 
Thank you my friend.
GeneralThank you for Voting, Russel In any case, we have performanc...memberShahin Khorshidnia27 Jan '11 - 12:51 
Thank you for Voting, Russel In any case, we have performance problem when suing big values in every codes.
GeneralReason for my vote of 5 Good But try RandomNumbers(1,100000...memberRusselSSC27 Jan '11 - 12:32 
Reason for my vote of 5 Good But try RandomNumbers(1,1000000000) ans see performance and memory usages
GeneralRe: Thank you for Voting, Russel In any case, we have performan...memberShahin Khorshidnia27 Jan '11 - 12:52 
Thank you for Voting, Russel   In any case, we have performance problem when we're using big values in every codes.
GeneralReason for my vote of 5 nice - have 5memberPranay Rana26 Jan '11 - 20:48 
Reason for my vote of 5 nice - have 5
GeneralRe: Thank you Panay RanamemberShahin Khorshidnia26 Jan '11 - 20:55 
Thank you Panay Rana

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 28 Jan 2011
Article Copyright 2011 by Shahin Khorshidnia
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid