To generate Random numbers from 1- 20 I need to pick selective and it should not be repetitive.
How to do this in C#
Note I need to loop through as like this
Just like i did:
list.Clear();
int count = 0;
while (count < 20)
{
int x = Random.Range(1, 21);
if (!list.Contains(x))
{
list.Add(x);
count++;
}
}
class Program
{
static void Main(string[] args)
{
List<int> list = new List<int>();
int val;
Random r;
int IntialCount = 1;
int count = 7 ;
int maxRandomValue = 8;
while (IntialCount <= count)
{
r = new Random();
val = r.Next(maxRandomValue);
if (!list.Contains(val))
{
list.Add(val);
IntialCount++;
}
}
}
}
static void Main(string[] args)
{
//Randomize 15 numbers out of 25 - from 1 to 25 - in ascending order
var randomNumbers = new List<int>();
var randomGenerator = new Random();
int initialCount = 1;
for (int i = 1; i <= 15; i++)
{
while (initialCount <= 15)
{
int num = randomGenerator.Next(1, 26);
if (!randomNumbers.Contains(num))
{
randomNumbers.Add(num);
initialCount++;
}
}
}
randomNumbers.Sort();
randomNumbers.ForEach(x => Console.WriteLine(x));
}
This method will generate all the numbers, and no numbers will be repeated:
/// <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);
}
}
You can use it like this:
Console.WriteLine("All numbers between 0 and 20 in random order:");
foreach (int i in UniqueRandom(0, 20)) {
Console.WriteLine(i);
}