Click here to Skip to main content
15,884,834 members
Please Sign up or sign in to vote.
3.67/5 (2 votes)
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
Updated 12-Jun-16 12:40pm
Comments
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.

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

How to generate many random various numbers?

I recommend looking at alternative 1
 
Share this answer
 
See my tip: "Random extraction of 5 cards from a deck"[^], it is C++ but you should get the idea.
 
Share this answer
 
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.
C#
List<int> available = new List<int>(5000);
for(int i=1; i<=5000; i++)
  available.Add(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.
C#
List<int> result = new List<int>(5000);
while(available.Count > 0)
{
  int index = random.Next(availableCount);
  result.Add(available[index]);
  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.
 
Share this answer
 
Comments
dr.m-rostami 27-Sep-12 17:20pm    
this is the best solution
thx all
ketan italiya 26-Dec-13 6:59am    
superb solution..
[no name] 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...
Try this snippet
C#
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))
                    {
                        result.Add(number);
                    }
                }
            }
            else
            {
                Console.WriteLine("Select another boundaries or number count");
            }
            return result;
        }
 
Share this answer
 
Comments
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.

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#.



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);
           }
           Console.ReadLine();
       }
 
Share this answer
 
v2
Comments
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!)
Link[^]
 
Share this answer
 
Comments
Simon Bang Terkildsen 24-Aug-11 8:29am    
This doesn't solve the OP's problem.
i'm colecting all solution and this is the result:
C#
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++)
                    available.Add(i);
                List<int> result = new List<int>(number);
                while (available.Count > 0)
                {
                    int index = r.Next(available.Count);
                    result.Add(available[index]);
                    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));
        }
    }
}
 
Share this answer
 
v2
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)
C#
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
C#
public void d()
{
int TargetRange = 5000;
List<int> NumberPool = new List<int>();
for (int i = 0; i < TargetRange ; i++)
{
NumberPool.Add(i);
}

List<int> Muddle = new List<int>();
for (int i = 0; i < TargetRange ; i++)
{
int r = random.Next(0, NumberPool.Count);
Muddle.Add(r);
NumberPool.Remove(r); 
}
}
 
Share this answer
 
v3
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;
}
 
Share this answer
 
Comments
Philippe Mori 12-Jun-16 19:16pm    
Use code blocks.
Try this it may improve speed of execution
C#
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);
    result.Add(index);
    ht[index] = "1";
}
ht.Clear();
 
Share this answer
 
v2
I thought I would add a one liner just for completeness.
C#
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 [^]
 
Share this answer
 
v2

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900