我希望使用密钥随机洗牌列表/数组。我希望能够使用密钥重复相同的随机顺序。
所以我将从1到20随机生成一个数字键,然后使用该键尝试随机洗牌。
我首先尝试使用密钥继续遍历我的列表,递减密钥直到= 0,然后抓取我所在的任何元素,将其删除并将其添加到我的混洗数组中。结果是随机的,但是当阵列很小(我的大部分都是)和/或键很小时它不会最终改组......似乎更像是一个转变。
我必须能够确定
的顺序以下是csharp中的一些示例代码:
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];
}
}
答案 0 :(得分:1)
进行随机排列,用钥匙为RNG播种。
/**
* 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));
}
}
答案 1 :(得分:0)
实施Fisher-Yates之类的内容。不要自己动手。这可能是错的。 Seed the Random constructor具有指定值。洗牌将是可重复的。
或者,这可以通过linq很好地完成:
var key=0;
var r=new Random(key);
myList.OrderBy(x=>r.Next());
更改key
的值以更改随机播放。