[英]Generate Random int number outside given List<int>
我目前正在嘗試找到一種在給定列表之外生成隨機數的方法。
我做了這個
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;
}
它工作(有點)很好(在調用這個函數后,我的 FPS 有一個短暫的下降,比如 10 毫秒)。
但是我一直想知道,“有沒有更好的方法來做到這一點?” 或“System.Linq 是否有一個比該代碼更快的 function?”
如果有更好的方法,你能告訴我嗎? 謝謝你的洞察力。 :)
恕我直言,您應該預先初始化所有可能的值,然后重新排列列表。
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
您可以在這里找到更好的 shuffle 替代方案:
編輯:
這里沒有List<int>
的版本,而是使用Enumerable.Range(start, count);
_randomNumbers = new Queue<int>(Enumerable.Range(min, max - min).OrderBy(x => Guid.NewGuid()));
https://dotnetfiddle.net/S8aDuE
編輯2:
根據大眾的需求,這里有一個更好的洗牌替代品之一的版本
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.