I was able to write a function that can generate "unique && random" integers within a range. But this in n 2 . I'm using it for 6 random ints at one place and 30 random ints at other, so how can we improve it if there's a need to improve it?
private int[] genRands(int max, int totalRandomIntsRequired)
{
int[] nums = new int[totalRandomIntsRequired];
Random r = new Random();
for (int i = 0; i < totalRandomIntsRequired; i++)
{
nums[i] = r.Next(0, max + 1);
for (int j = i; j >= 0; j--)
{
if(nums[i] == nums[j])
{
nums[i] = r.Next(0, max + 1);
}
}
}
return nums;
}
here is a approach with a HashSet
which does not allow duplicates and as a efficient internal duplicate check.
public static int[] genRands(int total, int max)
{
if (max < total)
{
throw new IndexOutOfRangeException();
}
Random _random = new Random();
HashSet<int> Result = new HashSet<int>();
while (Result.Count < total)
{
Result.Add(_random.Next(0, max));
}
return Result.ToArray();
}
I'm a little confused in what you are asking, if you just need to generate 6 or n random numbers, why loop twice? Either way you can try out this
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
var rands = genRands(100, 6);
foreach (var num in rands.Select((n, i) => new { i= i + 1, n }))
{ Console.WriteLine(string.Format("[{0}] {1}", num.i, num.n));};
Console.ReadLine();
}
private static List<int> genRands(int max, int total)
{
var nums = new List<int>();
Random r = new Random();
for (int i = 0; i < total; i++)
nums.Add(r.Next(0, max));
return nums;
}
}
}
It should output something like this
[1] 45
[2] 29
[3] 40
[4] 75
[5] 29
[6] 57
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.