Generating random, unique values C#
I'm calling NewNumber() regularly, but the problem is I often get
repeated numbers.
Random.Next
doesn't guarantee the number to be unique. Also your range is from 0 to 10 and chances are you will get duplicate values. May be you can setup a list of int
and insert random numbers in the list after checking if it doesn't contain the duplicate. Something like:
public Random a = new Random(); // replace from new Random(DateTime.Now.Ticks.GetHashCode());
// Since similar code is done in default constructor internally
public List<int> randomList = new List<int>();
int MyNumber = 0;
private void NewNumber()
{
MyNumber = a.Next(0, 10);
if (!randomList.Contains(MyNumber))
randomList.Add(MyNumber);
}
c# unique random number
Here's the simple way to do it without creating a shuffle method for the List (though there are examples of that). Basically create a list of all possible integers, populate the list, then sort by new GUIDs.
int X = 20;
var RowNumbers = new List<int>();
for (int i = 0; i < X; i++)
RowNumbers.Add(i);
foreach (int i in RowNumbers.OrderBy(f => Guid.NewGuid()))
{
data.Rows[i][3] = i;
}
Generating random numbers without repeating.C#
Check each number that you generate against the previous numbers:
List<int> listNumbers = new List<int>();
int number;
for (int i = 0; i < 6; i++)
{
do {
number = rand.Next(1, 49);
} while (listNumbers.Contains(number));
listNumbers.Add(number);
}
Another approach is to create a list of possible numbers, and remove numbers that you pick from the list:
List<int> possible = Enumerable.Range(1, 48).ToList();
List<int> listNumbers = new List<int>();
for (int i = 0; i < 6; i++)
{
int index = rand.Next(0, possible.Count);
listNumbers.Add(possible[index]);
possible.RemoveAt(index);
}
Generate a unique random number between 1 and 10?
- Setup a list with all the valid values at Awake
- Get a random value from the list
- Remove the value from the list to avoid duplicates
- BONUS - You could also extend the class to set any min and max numbers
public class RandomGenerator : MonoBehaviour
{
public int minNumber = 1;
public int maxNumber = 10;
private List<int> _validNumbers;
public int number;
private void Awake()
{
_validNumbers = new List<int>();
for (int i = minNumber; i <= maxNumber; i++)
_validNumbers.Add(i);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
if (_validNumbers.Count == 0)
Debug.Log("No valid Numbers");
else
number = GetRandomNumber();
}
}
private int GetRandomNumber()
{
var nextIndex = Random.Range(0, _validNumbers.Count - 1);
var result = _validNumbers[nextIndex];
_validNumbers.RemoveAt(nextIndex);
return result;
}
}
EDIT AFTER COMMENTS:
This question is very similar to this other question. But Unity.Random is different than System.Random.
The answers offered in the other question work here too. But we have more choices here.
Constantly generating unique and random values in a specific range in C#
Here is a solution, that shuffles the values and returns each value until the list is exhausted, then starts all over:
int[] GenerateNewArray(int n)
{
// Define an array of values we wish to return and populate it
int[] baseValues = Enumerable.Range(1, n).ToArray();
Random rnd=new Random();
// Shuffle the array randomly using Linq
return baseValues.OrderBy(x => rnd.Next()).ToArray();
}
void Main()
{
int nNumbers = 10;
while (true)
{
// Generate a new randomized array
var values = GenerateNewArray(nNumbers);
// Print each value
for (int i=0;i<nNumbers;i++)
{
Console.WriteLine($"The number generated is {values[i]}");
}
}
}
EDIT
Parameterized the number of unique values.
Will this always generate UNIQUE RANDOM number each time?
Here is a very efficient way to do this task:
private Random rnd = new Random();
public int rand_num()
{
string exe_path = System.Windows.Forms.Application.ExecutablePath;
string exe_folder = System.IO.Path.GetDirectoryName(exe_path);
string file_path = System.IO.Path.Combine(exe_folder, "Invoices\numbers.txt");
var number =
Enumerable
.Range(0, 10000)
.Except(File.ReadAllLines(file_path).Select(x => int.Parse(x)))
.OrderBy(x => rnd.Next())
.First();
File.AppendAllLines(file_path, new [] { number.ToString() });
return number;
}
It generates a list of all of the numbers Enumerable.Range(0, 10000)
. It then removes the numbers that it already finds in the text file .Except(File.ReadAllLines(file_path).Select(x => int.Parse(x)))
. It then orders the remaining numbers randomly (like shuffling a pack of cards) .OrderBy(x => rnd.Next())
and finally it just selects the first number .First();
.
Related Topics
Difference Between Shadowing and Overriding in C#
How to Get the Current Username in .Net Using C#
How to Load Image to Wpf in Runtime
Show/Hide the Console Window of a C# Console Application
How to Save/Restore Serializable Object To/From File
Pass Extra Parameters to an Event Handler
How to Export Datatable to Excel
What Is the Purpose of the "Prefer 32-Bit" Setting in Visual Studio and How Does It Actually Work
How to Ensure That a Division of Integers Is Always Rounded Up
How to Strip Non-Ascii Characters from a String In C#
Use Linq to Get Items in One List≪≫, That Are Not in Another List≪≫