我有这段代码可以将数字从1改到17,然后将其放入文本框
使用While循环时发生问题
表单没有出现,并且计算需要很多时间
有什么问题吗?
这是我写的代码:
private void Level_1_Load(object sender, EventArgs e)
{
shuffle();
}
private void shuffle()
{
Random rand = new Random();
int randomNum;
int[] NumArr = new int[17];
int counter = 0;
bool IsDuplicate = false;
do
{
randomNum = rand.Next(17);
IsDuplicate = false;
for (int i = 0; i < NumArr.Length; i++)
{
if (NumArr[i] == randomNum)
{
IsDuplicate = true; break;
}
}
if (IsDuplicate == false)
{
NumArr[counter] = randomNum;
counter++;
}
} while (counter < 17);
TextBox1.Text = NumArr[0].ToString();
TextBox2.Text = NumArr[1].ToString();
TextBox3.Text = NumArr[2].ToString();
TextBox4.Text = NumArr[3].ToString();
TextBox5.Text = NumArr[4].ToString();
TextBox6.Text = NumArr[5].ToString();
TextBox7.Text = NumArr[6].ToString();
TextBox8.Text = NumArr[7].ToString();
TextBox9.Text = NumArr[8].ToString();
TextBox10.Text = NumArr[9].ToString();
TextBox11.Text = NumArr[10].ToString();
TextBox12.Text = NumArr[11].ToString();
TextBox13.Text = NumArr[12].ToString();
TextBox14.Text = NumArr[13].ToString();
TextBox15.Text = NumArr[14].ToString();
TextBox16.Text = NumArr[15].ToString();
TextBox17.Text = NumArr[16].ToString();
}
答案 0 :(得分:1)
最好用所需的数字初始化数组,然后将它们随机排列。像这样:
using System;
public class Program
{
public static void Main()
{
int[] numbers = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17};
shuffle(numbers);
Console.WriteLine(String.Join(", ", numbers));
}
private static void shuffle(int[] numbers)
{
Random r = new Random((int)DateTime.Now.Ticks);
for (int i = 0; i < numbers.Length; i++)
{
int temp = numbers[i];
int index = r.Next(numbers.Length);
numbers[i] = numbers[index];
numbers[index] = temp;
}
}
}
结果(每次运行都会有所不同)
9, 16, 12, 6, 3, 5, 4, 14, 15, 11, 8, 10, 17, 1, 2, 13, 7
答案 1 :(得分:0)
您可能想使用另一种算法来用非重复数字填充数组。
例如,使用[0、1、2、3、4 ...]初始化数组,然后将其随机播放。