问题描述
我正在寻找使用键随机地整理列表/数组的方法。我希望能够使用该键重复相同的随机顺序。
I am looking to randomly shuffle a list/array using a key. I want to be able to repeat the same random order using the key.
所以我将随机生成一个数字键,例如1到20,然后使用该键尝试
So I will randomly generate a numeric key from say 1 to 20 then use that key to try and randomly shuffle the list.
我首先尝试使用键来不断遍历我的列表,将键递减到0,然后抓住我所在的任何元素,将其删除并将其添加到我的随机数组中。结果是随机的,但是当数组很小(我的大部分将是)和/或键很小时,它最终并不会改组……似乎更多的是移位。
I first tried just using the key to keep iterating through my list, decrementing the key until=0, then grabbing whatever element I am on, removing it and adding it to my shuffled array. The result is kind of random but when the arrays are small (which most of mine will be) and/or the key is small it doesn't end up shuffling... seems to be more of a shift.
我必须能够确定
这是csharp中的一些示例代码:
Here is some sample code in csharp of :
public static TList<VoteSetupAnswer> ShuffleListWithKey(TList<VoteSetupAnswer> UnsortedList, int ShuffleKey)
{
TList<VoteSetupAnswer> SortedList = new TList<VoteSetupAnswer>();
int UnsortedListCount = UnsortedList.Count;
for (int i = 0; i < UnsortedListCount; i++)
{
int Location;
SortedList.Add(OneArrayCycle(UnsortedList, ShuffleKey, out Location));
UnsortedList.RemoveAt(Location);
}
return SortedList;
}
public static VoteSetupAnswer OneArrayCycle(TList<VoteSetupAnswer> array, int ShuffleKey, out int Location)
{
Location = 0;
if (ShuffleKey == 1)
{
Location = 0;
return array[0];
}
else
{
for (int x = 0; x <= ShuffleKey; x++)
{
if (x == ShuffleKey)
return array[Location];
Location++;
if (Location == array.Count)
Location = 0;
}
return array[Location];
}
}
推荐答案
/**
* Randomly permutes the array of this permutation. All permutations occur with approximately equal
* likelihood. This implementation traverses the permutation array forward, from the first element up to
* the second last, repeatedly swapping a randomly selected element into the "current position". Elements
* are randomly selected from the portion of the permutation array that runs from the current position to
* the last element, inclusive.
* <p>
* This method runs in linear time.
*/
public static void shuffle(Random random, int[] a) {
for (int i = 0; i < a.length - 1; i++) {
swap(a, i, i + random.nextInt(a.length - i));
}
}
这篇关于需要使用密钥进行可重复的随机数组随机播放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!