Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#
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
sacraj1K
Comments
johannesnestler at 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: bad
good
Please Sign up or sign in to vote.

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
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

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++)
  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.
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.
  Permalink  
Comments
dr.m-rostami at 27-Sep-12 17:20pm
   
this is the best solution
thx all
ketan italiya at 26-Dec-13 6:59am
   
superb solution..
Sibeesh Venu at 5-Aug-14 2:35am
   
+5
johannesnestler at 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);
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

See my tip: "Random extraction of 5 cards from a deck"[^], it is C++ but you should get the idea.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

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))
                    {
                        result.Add(number);
                    }
                }
            }
            else
            {
                Console.WriteLine("Select another boundaries or number count");
            }
            return result;
        }
  Permalink  
Comments
johannesnestler at 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: bad
good
Please Sign up or sign in to vote.

Solution 1

  Permalink  
Comments
Simon Bang Terkildsen at 24-Aug-11 8:29am
   
This doesn't solve the OP's problem.
Rate this: bad
good
Please Sign up or sign in to vote.

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++)
                    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));
        }
    }
}
  Permalink  
v2
Rate this: bad
good
Please Sign up or sign in to vote.

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++)
{
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); 
}
}
  Permalink  
v3
Rate this: bad
good
Please Sign up or sign in to vote.

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;
}
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

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);
                    result.Add(index);
                    ht[index] = "1";
                }
                ht.Clear();
  Permalink  
v2
Rate this: bad
good
Please Sign up or sign in to vote.

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 [^]
  Permalink  
v2

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

  Print Answers RSS
0 CHill60 330
1 OriginalGriff 285
2 CPallini 198
3 BillWoodruff 170
4 Sergey Alexandrovich Kryukov 168


Advertise | Privacy | Mobile
Web02 | 2.8.141015.1 | Last Updated 6 Aug 2014
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100