我在创建滑动拼图时遇到问题。我正在尝试制作一种方法来重置&洗牌所有15个按钮,但问题是随机数重复。
当我写bool[] usednum = new bool[array.length];
时出现错误,所以我增加了usednum数组的长度......
private void reset()
{
int[] array = { 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
int count = 0;
Random r = new Random();
bool[] usednum = new bool[50];
for (int i = 0; i < usednum.Length; i++)
usednum[i] = false;
while (count < array.Length)
{
int temp = array[r.Next(array.Length)];
if (usednum[temp] == false)
{
button1.Text = temp.ToString();
usednum[temp] = true;
count++;
}
temp = array[r.Next(array.Length)];
if (usednum[temp] == false)
{
button2.Text = temp.ToString();
usednum[temp] = true;
count++;
}
temp = array[r.Next(array.Length)];
if (usednum[temp] == false)
{
button3.Text = temp.ToString();
usednum[temp] = true;
count++;
}
temp = array[r.Next(array.Length)];
if (usednum[temp] == false)
{
button4.Text = temp.ToString();
usednum[temp] = true;
count++;
}
temp = array[r.Next(array.Length)];
if(usednum[temp] == false)
{
button5.Text = temp.ToString();
usednum[temp] = true;
count++;
}
temp = array[r.Next(array.Length)];
if (usednum[temp] == false)
{
button6.Text = temp.ToString();
usednum[temp] = true;
count++;
}
/*.
.
.
. to button 15*/
答案 0 :(得分:0)
只需将数组洗牌:http://en.wikipedia.org/wiki/Shuffling
一个简单的shuffle算法(伪代码)
maxIndex = array.Length - 1
for index in 0 to maxIndex - 1
swapIndex = random number between index and maxIndex
swap (array, index, swapIndex)
答案 1 :(得分:0)
而不是使用静态数组使用列表
var array = new int[] { 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
var unused = array.ToList();
var r = new Random();
while (unused.Count > 0)
{
int c = r.Next(unused.Count - 1);
int current = unused[c];
unused.RemoveAt(c);
//...
}