Non duplicate random numbers in C# [duplicate] - c#

This question already has answers here:
Random.Next returns always the same values [duplicate]
(4 answers)
Closed 9 years ago.
I am trying to create a range of non duplicate random numbers between 1 - 10, I planned on doing this by storing each random number I made in to an array and then checking that array every time to make sure I ain't already used the number.
My problem is that instead of creating different random numbers such as 1, 2, 3 I just keep getting the same random number over and over.
randomNumber();
Label1.Text = randomRow + "";
randomNumber();
Label2.Text = randomRow + "";
randomNumber();
Label3.Text = randomRow + "";
public int randomNumber()
{
List<int> numbers = new List<int>();
int num = 0;
Random randNum = new Random();
num = randNum.Next(1, 11);
if (numbers.Contains(num))
{
num = randNum.Next(1, 11);
}
else
{
randomRow = num;
numbers.Add(num);
}
return randomRow;
}

Problem : everytime you are creating the RandomNumber object in too close time.
When you create a Random object, it's seeded with a value from the system clock. If you create Random instances too close in time, they will all be seeded with the same random sequence.
From Here
When you create a Random object, it's seeded with a value from the
system clock. If you create Random instances too close in time, they
will all be seeded with the same random sequence.
Solution :
move Random randNum = new Random(); outside the function randomNumber().
Try This:
Random randNum = new Random();
public int randomNumber()
{
List<int> numbers = new List<int>();
int num = 0;
num = randNum.Next(1, 11);
if (numbers.Contains(num))
{
num = randNum.Next(1, 11);
}
else
{
randomRow = num;
numbers.Add(num);
}
return randomRow;
}

My best gues is that you are using this in a loop. In this case because you declare
Random randNum = new Random();
evry time this will generate tha same number. Just declare it BEFORE the loop and it should be fine.
Also you should consider a different approch because it is not a good practice. Like:
int[] array = {1,2,3,4,5,6,7,8,9,10};
Random randNum = new Random();
int rand=0;
int temp;
for(int i = 0; i<10;i++)
{
rand = randNum.next(1,10-i);
temp=array[rand];
array[rand]=array[9-i];
array[9-i]=temp;
}

Related

Unique 4 digit random number in C#

I want to generate an unique 4 digit random number. This is the below code what I have tried:
Code for generating random number
//Generate RandomNo
public int GenerateRandomNo()
{
int _min = 0000;
int _max = 9999;
Random _rdm = new Random();
return _rdm.Next(_min, _max);
}
The problem is I have received a random no with value 241 which is not a 4 digit number. Is there any problems with the code?
//Generate RandomNo
public int GenerateRandomNo()
{
int _min = 1000;
int _max = 9999;
Random _rdm = new Random();
return _rdm.Next(_min, _max);
}
you need a 4 digit code, start with 1000
private Random _random = new Random();
public string GenerateRandomNo()
{
return _random.Next(0, 9999).ToString("D4");
}
241 is a four digit number, if you use leading zeros: 0241.
Display the returned number with a format string like this:
String.Format("{0:0000}", n);
Just one line code
int num = new Random().Next(1000, 9999);
0 is the same as 0000.
241 is the same as 0241.
You could format the integer to a string with a leading zero.
Random generator = new Random();
string number = generator.Next(1, 10000).ToString("D4");
use: int _min = 1000;
or use leading 0 in case if you want 0241
I suggest to create new list and check if this list contains any of number
var IdList = new List<int>();
do
{
billId = random.Next(1, 9000);
} while (IdList.Contains(billId));
IdList.Add(billId);
int NoDigits = 4;
Random rnd = new Random();
textBox2.Text = rnd.Next((int)Math.Pow(10, (NoDigits - 1)), (int)Math.Pow(10, NoDigits) -1).ToString();
Expanding on the answer from brij but with 0000 to 9999 rather than 1000 to 9999
string formatting = "0000"; //Will pad out to four digits if under 1000
int _min = 0;
int _max = 9999;
Random randomNumber = new Random();
var randomNumberString = randomNumber.Next(_min, _max).ToString(formatting);
or if you want to minimalize lines:
Random randomNumber = new Random();
var randomNumberString = randomNumber.Next(0, 9999).ToString("0000");
Using this you will avoid starting numbers with 00[...] and you can also specify the length.
string RandomNumbers(int Length)
{
Random Rand = new Random();
StringBuilder SB = new StringBuilder();
for (int i = 0; i < Length; i++)
SB.Append(Rand.Next(0, 9));
return SB.ToString();
}
RandomNumbers(4) // OUTPUT: 9301, 4936, 0692, etc ...
Here is Method to generate any digits number. The loop inside will regenerate the number if it contains duplicate digits, so the random number will consist from unique digits only.
using System.Linq;
public static int GenerateRandomNum()
{
// Number of digits for random number to generate
int randomDigits = 4;
int _max = (int)Math.Pow(10, randomDigits);
Random _rdm = new Random();
int _out = _rdm.Next(0, _max);
while (randomDigits != _out.ToString().ToArray().Distinct().Count())
{
_out = _rdm.Next(0, _max);
}
return _out;
}
You can consider something like this.
int length = 4;
int number = 50;
string asString = number.ToString("D" + length);
The above code gives the result 0050.
Similarly you can try converting to string and verify.

Two random class returning same value [duplicate]

This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 7 years ago.
i tried to create random string contains both int and string. Below is the classes of how i get random string and int.
private int RandomNumber1(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
private int RandomNumber2(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
private string RandomStringSatu(int size, bool uppercase)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
if (uppercase)
return builder.ToString().ToUpper();
return builder.ToString();
}
private string RandomStringDua(int size, bool uppercase)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
if (uppercase)
return builder.ToString().ToUpper();
return builder.ToString();
}
And here is the way i set up those classes to get a random string.
StringBuilder sb = new StringBuilder();
sb.Append(RandomStringSatu(1, true));
sb.Append(RandomNumber1(1, 9));
sb.Append(RandomStringDua(1, true));
sb.Append(RandomNumber2(1, 9));
string rdmKode = sb.ToString();
this is the result that i get :
Result
On the picture you can see that the first two caracters has same value with the last two caracter.
Now, the question is what should i do, if i want to get different caracter.
So, the output should be looks like "D2B1"
Thanks
If you move your Random random = new Random(); line from RandomNumber1 and RandomNumber2 to global to outside of methods, than use that rundom field in that RandomNumber1 and RandomNumber2 methods result will be differente.
Thanx Jamaxack
Using an answer from this stackoverflow question
You are looking to seed when you create a new instance.
Random random = new Random(Guid.NewGuid().GetHashCode());
Provide different seed values when you create instances of Random() to generate different values. Check documentation here, https://msdn.microsoft.com/en-us/library/ctssatww%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

How to generate unique random integers that do not duplicate

I have created a short program that creates 3 random integers between 1-9 and stores them in an array, however, I would not like any of them to repeat, that is, I would like each to be unique. Is there an easier way to generate 3 unique integers other than having to iterate through the array and comparing each integer to each other? That just seems so tedious if I were to increase my array to beyond 3 integers.
This is my code to generate 3 random numbers. I saw other code in Java, but I thought maybe C# has a easier and more efficient way to do it.
var number = new Numbers[3];
Random r = new Random();
for ( int i = 0; i < number.Length; i++)
{
number[i] = new Numbers(r.Next(1,9));
}
Console.WriteLine("The Three Random Numbers Are:");
foreach(Numbers num in number)
{
Console.WriteLine("{0}", num.Number);
}
I would do something like this:
var range = Enumerable.Range(1, 8);
var rnd = new Random();
var listInts = range.OrderBy(i => rnd.Next()).Take(3).ToList();
You could make an array or a list of the numbers that might be generated, e.g. 0, 1, 2, 3. Then you generate a number from 0 to this list's length, e.g. 2 and pick list[2] so for the next time you only have 0, 1, 3 in your list.
It takes longer to generate it, especially for long lists but it doesn't repeat numbers.
using System;
using System.Collections.Generic;
public class Test
{
static Random random = new Random();
public static List<int> GenerateRandom(int count)
{
// generate count random values.
HashSet<int> candidates = new HashSet<int>();
// top will overflow to Int32.MinValue at the end of the loop
for (Int32 top = Int32.MaxValue - count + 1; top > 0; top++)
{
// May strike a duplicate.
if (!candidates.Add(random.Next(top))) {
candidates.Add(top);
}
}
// load them in to a list.
List<int> result = new List<int>();
result.AddRange(candidates);
// shuffle the results:
int i = result.Count;
while (i > 1)
{
i--;
int k = random.Next(i + 1);
int value = result[k];
result[k] = result[i];
result[i] = value;
}
return result;
}
public static void Main()
{
List<int> vals = GenerateRandom(10);
Console.WriteLine("Result: " + vals.Count);
vals.ForEach(Console.WriteLine);
}
}
Grate explanation and answers from here
Source http://ideone.com/Zjpzdh

C# - Writing numbers 1 through 10 in random order [duplicate]

This question already has answers here:
Is using Random and OrderBy a good shuffle algorithm? [closed]
(13 answers)
Closed 9 years ago.
Part 1: All I am wanting to achieve is to write the numbers 1, 2, 3 ... 8, 9, 10 to the console window in random order. So all the numbers will need to be written to console window, but the order of them must be random.
Part 2: In my actual project I plan to write all of the elements in an array, to the console window in random order. I am assuming that if I can get the answer to part 1, I should easily be able to implement this with an array.
/// <summary>
/// Returns all numbers, between min and max inclusive, once in a random sequence.
/// </summary>
IEnumerable<int> UniqueRandom(int minInclusive, int maxInclusive)
{
List<int> candidates = new List<int>();
for (int i = minInclusive; i <= maxInclusive; i++)
{
candidates.Add(i);
}
Random rnd = new Random();
while (candidates.Count > 0)
{
int index = rnd.Next(candidates.Count);
yield return candidates[index];
candidates.RemoveAt(index);
}
}
In your program
Console.WriteLine("All numbers between 0 and 10 in random order:");
foreach (int i in UniqueRandom(0, 10)) {
Console.WriteLine(i);
}
Enumerable.Range(1, 10).OrderBy(i => Guid.NewGuid()) works nicely.
using System;
using System.Collections;
namespace ConsoleApplication
{
class Numbers
{
public ArrayList RandomNumbers(int max)
{
// Create an ArrayList object that will hold the numbers
ArrayList lstNumbers = new ArrayList();
// The Random class will be used to generate numbers
Random rndNumber = new Random();
// Generate a random number between 1 and the Max
int number = rndNumber.Next(1, max + 1);
// Add this first random number to the list
lstNumbers.Add(number);
// Set a count of numbers to 0 to start
int count = 0;
do // Repeatedly...
{
// ... generate a random number between 1 and the Max
number = rndNumber.Next(1, max + 1);
// If the newly generated number in not yet in the list...
if (!lstNumbers.Contains(number))
{
// ... add it
lstNumbers.Add(number);
}
// Increase the count
count++;
} while (count <= 10 * max); // Do that again
// Once the list is built, return it
return lstNumbers;
}
}
Main
class Program
{
static int Main()
{
Numbers nbs = new Numbers();
const int Total = 10;
ArrayList lstNumbers = nbs.RandomNumbers(Total);
for (int i = 0; i < lstNumbers.Count; i++)
Console.WriteLine("{0}", lstNumbers[i].ToString());
return 0;
}
}
}
int[] ints = new int[11];
Random rand = new Random();
Random is a class built into .NET, and allows us to create random integers really, really easily. Basically all we have to do is call a method inside our rand object to get that random number, which is nice. So, inside our loop, we just set each element to the results of that method:
for (int i = 0; i < ints.Length; i++)
{
ints[i] = rand.Next(11);
}
We are essentially filling our entire array with random numbers here, all between 0 and 10. At this point all we have to do is display the contents for the user, which can be done with a foreach loop:
foreach (int i in ints)
{
Console.WriteLine(i.ToString());
}

Generating random numbers 1-100

I need to generate random numbers from 1 to 100 and I know how to do that part...
I need to ask user how many numbers he wants to generate(if he says 5 the program needs to generate 5 numbers from 1 to 100). I only now how to make a fixable amount by adding new int's in a list.
I did achieve that before, but then i couldn't make it work, so it would write average of those numbers and min+max value.
Here is my code below:
Random k = new Random();
//here i added in the same way other variables and put them in a list
int j = k.Next(100);
Console.WriteLine("");
double[] list1 = {j};
double povp = list1.Average();
Console.WriteLine(povp);
Console.WriteLine("");
Console.WriteLine(list1.Max());
Console.WriteLine("");
Console.WriteLine(list1.Min());
Console.ReadKey();
You could use the following code to generate N numbers:
IEnumerable<int> numbers = Enumerable.Repeat(1,N).Select(_ => random.Next(100));
// ask user for input
string input = Console.Readline();
int parsed;
// parse to int, needs error checking (will throw exception when input is not a valid int)
int.TryParse(input, out parsed);
Random random = new Random();
List<double> list = new List<double>();
for(int i = 0; i < parsed; parsed++)
{
list.Add(random.Next(100));
}
public void Main()
{
const int NUMBERS_FROM = 1;
const int NUMBERS_TO = 100;
int n = int.Parse(Console.ReadLine());
Random rnd = new Random();
List<int> numbers = new List<int>();
for (int i = 0; i < n; i++)
{
int rndNumber = rnd.Next(NUMBERS_FROM, NUMBERS_TO + 1);
numbers.Add(rndNumber);
}
Console.WriteLine("Numbers : {0}",string.Join(", ",numbers));
}
this will generate N numbers and add them to a list and then print them to the console. I think this is what you were looking for

Categories