【发布时间】:2025-12-30 00:55:07
【问题描述】:
我有两个数组,一个是 PictureBox 数组,另一个是 Integer 数组,它们都有相同数量的元素。我希望两个数组每次都随机打乱,但都以相同的方式打乱。
如果我使用两个 PictureBox 数组或两个 Integer 数组,这是一个有效的代码,但是我希望它随机播放一个 PictureBox 数组和一个 Integer 数组。
这是我想要工作的代码:(两个不同的数组)
PictureBox[] cards = new PictureBox[13];
// PictureBox[] numValue = new PictureBox[13];
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10 };
Random rnd = new Random();
for (int i = 0; i < cards.Length - 1; i++)
{
int j = rnd.Next(i, cards.Length);
PictureBox temp = cards[j];
cards[j] = cards[i];
cards[i] = temp;
temp = numbers[j]; //An error occurs here because numbers is not a PictureBox variable
numbers[j] = numbers[i];
numbers[i] = temp;
}
这是有效的代码:(对于相同的数组)
PictureBox[] numValue = new PictureBox[13];
PictureBox[] cards = new PictureBox[13];
// int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10 };
Random rnd = new Random();
for (int i = 0; i < cards.Length - 1; i++)
{
int j = rnd.Next(i, cards.Length);
PictureBox temp = cards[j];
cards[j] = cards[i];
cards[i] = temp;
temp = numValue [j];
numValue [j] = numValue [i];
numValue [i] = temp;
}
如果您知道其他可以帮助我的不同代码,请随时分享!
【问题讨论】:
-
我建议你创建
Dictionary<int, PictureBox>然后你可以使用随机的int来访问它们,这是关键。 -
恕我直言,拥有一个具有
PictureBox和int属性的类数组会更简洁。
标签: c# arrays random fisher-yates-shuffle