12,452,056 members (42,784 online)
Rate this:
See more:
How to generate Random numbers without repeating any numbers in the given target like(1-5000) there should be no reparation and I should be able to get 5000 randomized numbers. I should be able to run the randomized as many times as the user wants,How to do with C#?.

For Sample
Target is (1-10)
No of times to run =2

First run:
5,4,6,8,3,1,2,0,7,10
second run
6,3,5,8,4,2,0,1,10,7

Like this I should be able to get the results as many times as I run..
Posted 24-Aug-11 1:52am
sacraj1.1K
Updated 12-Jun-16 12:40pm
johannesnestler 5-Aug-14 13:04pm

Off-Topic: Amazing what - ahh - "not so good" answers you got for this simple problem: constructing strings, messing arround with Dictionaries and HashTables, optimizing the code for worst performance possible :-) only Paulo Zemek showed the obviouse high performing solution ... I shudder when I think about how all the games and applications using such kind of random "decks" are implemented.

Rate this:

Solution 6

I believe the tip linked below covers what you are after.

How to generate many random various numbers?

I recommend looking at alternative 1
Rate this:

Solution 2

See my tip: "Random extraction of 5 cards from a deck"[^], it is `C++` but you should get the idea.
Rate this:

Solution 4

The first solution may work, but it will start to become slower the more numbers were already chosen. (after all, after having 4999 numbers selected there is only one possibility, but it may be generating any value, needing to try again, and again, and again).

One thing that may make it faster is using a HashSet instead a list, as searching in a HashSet is faster. But my real solution is different.

First we create a list which all possible values.
```List<int> available = new List<int>(5000);
for(int i=1; i<=5000; i++)
```

Then, we will keep generating random indexes (instead of random values). Such indexes will be used to get the value from the available list, put it in the result and then remove it from the available list.
```List<int> result = new List<int>(5000);
while(available.Count > 0)
{
int index = random.Next(availableCount);
available.RemoveAt(index);
}

return result;
```

This way, if you create a list with 1 million values, you will have only 1 million calls to `random.Next();`
Surely the list itself has its own problems, but it is better than keep waiting until the last available number is guess.
dr.m-rostami 27-Sep-12 17:20pm

this is the best solution
thx all
ketan italiya 26-Dec-13 6:59am

superb solution..
Sibeesh Venu 5-Aug-14 2:35am

+5
johannesnestler 5-Aug-14 7:52am

Very good 5ed - Suggestion of small improvement: When you generate your initial list you could use some "linq sugar" to make it even cleaner: System.Linq.Enumerable.Range(0, 5000);
Philippe Mori 12-Jun-16 19:15pm

Well for relatively large list, this solution is not very efficient as you would make a lot of copying while removing items...
Rate this:

Solution 3

Try this snippet
```private static List<int> Randomize(int count, int min, int max)
{
Random r = new Random();
List<int> result = new List<int>();
if (count < max - min)
{
while (result.Count <= count)
{
int number = r.Next(min, max);
if (!result.Contains(number))
{
}
}
}
else
{
Console.WriteLine("Select another boundaries or number count");
}
return result;
}```
johannesnestler 5-Aug-14 7:51am

very poor performance if you do it like this. the Contains operation alone... This code is nothing you want to see in any softwaresystem - I even wouldn't write that as homework - forget it.
Rate this:

Solution 15

I realise that this is an old question and I would not normally respond but I feel that the best solution has not been explored. It seems to me that the question is asking for a method that shuffles a data set. There is a well established algorithm that does this called the Fisher-Yates Shuffle. Here is an implementation in C#.

```private static void FisherYatesShuffle<T>(IList<T> list)
{
int count = list.Count;
var random = new Random();

for (int i = 0; i < count; i++)
{
//Randomly set n to a value >=i but<count
int n = random.Next(i, count);
//swap the contents of list[n] with those of list[i]
T temp = list[n];
list[n] = list[i];
list[i] = temp;
}
}

private static void Main()
{
int[] list = Enumerable.Range(1, 50).ToArray();
FisherYatesShuffle(list);
foreach (int value in list)
{
Console.WriteLine(value);
}
}
```
v2
Matt T Heffron 13-Jun-16 17:26pm

Yes.
I posted a similar solution a couple of years ago: playing cards game - Solution 3
If avoiding bias in the resultant "shuffles" is important, pay particular attention to the Potential sources of bias in the Wikipedia article. (For example, to have an unbiased shuffling of a 52 card deck the pseudo random number generator must have at least 226 bits of internal state!)
Rate this:

Solution 1

Simon Bang Terkildsen 24-Aug-11 8:29am

This doesn't solve the OP's problem.
Rate this:

Solution 7

i'm colecting all solution and this is the result:
```using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;

namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
public static Random r=new Random();
public static int number;
protected void Page_Load(object sender, EventArgs e)
{

}

protected void ASPxButton1_Click(object sender, EventArgs e)
{
//creat a text box in desing mode and call it ASPxTextBox1
if (ASPxTextBox1.Text == "")
{
Response.Write("first enter you count number");
}
else
{
number = Convert.ToInt32(ASPxTextBox1.Text);
List<int> available = new List<int>(number);
for (int i = 1; i <= number; i++)
List<int> result = new List<int>(number);
while (available.Count > 0)
{
int index = r.Next(available.Count);
available.RemoveAt(index);
}
for (int i = 0; i < result.Count; i++)
{
Response.Write(result[i] + "-");
}
}
}

protected int Pro_R(int min, int max)
{
return (r.Next(min, max));
}
}
}```
v2
Rate this:

Solution 9

I usaly use a globalized random number generator so my application dosen't load the same number combos repeatedly.
(place this in a global area)
`static System.Random random = new Random();`
Then you can make a list of ALL numbers in your target range and delete em as you muddle
```public void d()
{
int TargetRange = 5000;
List<int> NumberPool = new List<int>();
for (int i = 0; i < TargetRange ; i++)
{
}

List<int> Muddle = new List<int>();
for (int i = 0; i < TargetRange ; i++)
{
int r = random.Next(0, NumberPool.Count);
NumberPool.Remove(r);
}
}```
v3
Rate this:

Solution 11

public string generatrnumber()
{

Random rnd = new Random();
int val;

string outstr = "";

for (int i = 0; i < 7; ++i)
{

val = rnd.Next(0, 62);

if (val < 26)

outstr += (char)(val + 'a');

else if (val < 52)

outstr += (char)('A' + (val - 26));

else
{

outstr += (char)('0' + (val - 52));

}

}
return outstr;
}
Philippe Mori 12-Jun-16 19:16pm

Use code blocks.
Rate this:

Solution 12

Try this it may improve speed of execution
```Random random = new Random();
Hashtable ht = new Hashtable();
int totalItems = 5000;
int maxValue = totalItems + 1;

List<int> result = new List<int>(totalItems);
for (int x = 0; x < totalItems; x++)
{
int index = random.Next(0, maxValue);
while (ht[index] != null) index = random.Next(0, maxValue);
ht[index] = "1";
}
ht.Clear();
```
v2
Rate this:

Solution 13

I thought I would add a one liner just for completeness.
`var randomList = Enumerable.Range(1, 10).OrderBy(x => Guid.NewGuid());`

This will result in a list of 10 randomized numbers ranging from 1 to 10
The `OrderBy `extension with `Guid.NewGuid` ensures that the list is always random regardless of how many times it count. (Taking in account of course the randomnize of a the NewGuid Method. see [^]
v2

Top Experts
Last 24hrsThis month
 ppolymorphe 194 Maciej Los 145 Richard MacCutchan 115 OriginalGriff 110 Dave Kreskowiak 90
 OriginalGriff 6,123 ppolymorphe 3,755 Karthik Bangalore 3,545 Maciej Los 3,075 Richard Deeming 2,835