问题
I want to load scenes randomly without repetition using c#. Any help would do. Thanks.
int[] array = new int[] { 1, 2, 3, 4, 6, 8, 9, 10, 11, 12 };
List<int> list = new List<int>();
void Start()
{
list.AddRange(array);
}
int GetUniqueRandom(bool RemoveFromTheList)
{
if (list.Count == 0)
{
if (RemoveFromTheList)
{
list.AddRange(array);
}
else
{
return -1; // never repeat
}
}
int rand = Random.Range(0, 10);
int value = list[rand];
list.RemoveAt(rand); return value;
}
回答1:
A nice clean way is to shuffle the array, then put all the elements in a stack. All you need to get a random element is to pop an item off the stack.
You will want to remove the list in the list of fields and replace with this;
Stack remainingScenes = new Stack();
Remove the content of the Start() method - you don't need it.
In your method to get a new number;
if (remainingScenes.Count == 0) {
int n = array.Length;
while (n > 1)
{
int k = rng.Next(n--);
T temp = array[n];
array[n] = array[k];
array[k] = temp;
}
foreach(var element in array) {
remainingScenes.Push(element);
}
}
return remainingScenes.Pop();
The shuffle method is from here.
回答2:
Uhmmm, this looks very straightforward. Judging from your code, you only need a little modification to make it work..
List<int> list = new List<int>() { 1, 2, 3, 4, 6, 8, 9, 10, 11, 12 };
int GetUniqueRandom(bool RemoveFromTheList)
{
if (list.Count == 0)
{
return -1;//nothing in the list so return negative value
}
//generate random index from list
int randIndex = Random.Range(0, list.Count - 1);
int value = list[rand];
if(RemoveFromTheList)
{
list.RemoveAt(randIndex);
}
return value;
}
回答3:
Try this:
int[] array = new int[] { 1, 2, 3, 4, 6, 8, 9, 10, 11, 12 };
Stack<int> stack = null;
Then initialize like this:
var rnd = new Random();
stack = new Stack<int>(array.OrderBy(x => rnd.Next()));
Now you just keep getting values from the stack until it is empty:
var value = stack.Pop();
来源:https://stackoverflow.com/questions/38940689/load-random-scenes-without-repetition-using-c-sharp