在这种情况下,我正在试图对图像的LinkedList进行随机化或随机化,但是我设置它的方式似乎是无条件地继续下去
改组很简单,你有列表,记下最后一个条目,然后取第一个条目并把它放在列表中的随机位置,然后是下一个条目,等等,直到顶部条目是你注意到的条目最后,你将该条目放在列表中的随机位置,然后对列表进行洗牌.
这是我的代码:
class ShuffleClass
{
private LinkedList<Image> library;
private Image lastCard;
private Image topCard;
private Random rng;
private int place;
private LinkedListNode<Image> node;
public LinkedList<Image> shuffle(LinkedList<Image> library)
{
this.library = library;
lastCard = library.Last.Value;
rng = new Random();
while (library.First.Value != lastCard)
{
topCard = library.First.Value;
library.RemoveFirst();
place = rng.Next(1,library.Count+1);
if (place == library.Count)
{
library.AddBefore(library.Last, topCard);
}
else
{
node = library.Find(library.ElementAt(place));
library.AddBefore(node, topCard);
}
}
topCard = library.First.Value;
library.RemoveFirst();
place = rng.Next(0,library.Count+1);
if(place == library.Count)
{
library.AddBefore(library.Last, topCard);
}
else
{
node = library.Find(library.ElementAt(place));
library.AddBefore(node, topCard);
}
return library;
}
}
最佳答案 您可以使用随机类来混洗列表:
public static void Shuffle()
{
Random Rand = new Random();
LinkedList<int> list = new LinkedList<int>(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 });
foreach (int i in list)
Console.Write("{0} ", i);
Console.WriteLine();
int size = list.Count;
//Shuffle the list
list = new LinkedList<int>(list.OrderBy((o) =>
{
return (Rand.Next() % size);
}));
foreach (int i in list)
Console.Write("{0} ", i);
Console.WriteLine();
}
输出可能是这样的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
10 2 17 7 9 15 8 14 1 12 13 16 4 18 3 5 11 20 19 6