I am currently trying to find a way to generate a random number outside given list.
I did this
public static int getNewNumberOutsideGivenList(List<int> _list, int _min, int _max)
{
int a = 0;
// I use "Unity.Random", but as C# user you guys can use System.Random function
a = UnityEngine.Random.Range(_min, _max +1);
while (_list.Contains(a))
a = UnityEngine.Random.Range(_min, _max + 1);
return a;
}
It works(kinda) well (I got a short drop in FPS like 10ms after calling this function).
However i keep wondering, "is there a better way to do this?" or "does System.Linq has a function that is faster than that code?"
Can you please enlightened me if there exist a better way? Thank yoouuu for your insight. :)
IMHO you should pre intialize all possible values and than shuffle the list.
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
static Queue<int> _randomNumbers;
static Program()
{
var min = 0;
var max = 10;
var list = new List<int>();
for (int i = min; i < max; i++)
list.Add(i);
_randomNumbers = new Queue<int>(list.OrderBy(x => Guid.NewGuid()));
}
public static void Main()
{
while (true)
{
var next = GetNext();
if (next is null)
break;
Console.WriteLine(next);
}
}
static int? GetNext() => _randomNumbers.Count == 0 ? null : _randomNumbers.Dequeue();
}
https://dotnetfiddle.net/pBsmyH
You may find a better shuffle alternative here:
Edit:
Here a version without the List<int>
but instead it uses Enumerable.Range(start, count);
_randomNumbers = new Queue<int>(Enumerable.Range(min, max - min).OrderBy(x => Guid.NewGuid()));
https://dotnetfiddle.net/S8aDuE
Edit2:
By popular demand here a version with one of the better shuffle alternatives
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
static Queue<int> _randomNumbers;
static Random rng = new Random();
static Program()
{
var min = 0;
var max = 10;
var list = new List<int>();
for (int i = min; i < max; i++)
list.Add(i);
Shuffle(list);
_randomNumbers = new Queue<int>(list);
static void Shuffle<T>(IList<T> list)
{
int n = list.Count;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
(list[k], list[n]) = (list[n], list[k]); //Notice: I incorporated @MatthewWatson's idea, so it is slightly different than the one you find on the posted SO page
}
}
}
public static void Main()
{
while (true)
{
var next = GetNext();
if (next is null)
break;
Console.WriteLine(next);
}
}
static int? GetNext() => _randomNumbers.Count == 0 ? null : _randomNumbers.Dequeue();
}
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.