摘要:[C Sharp] 不重複亂數陣列
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsRandom01
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int i=0,k=1,o,temp;
string str="";
int[] AryRandom = new int[49];
Random RandomClass = new Random();
for (i=1; i < 50; i++)//將範圍1至49的整數依序存放於陣列中
{
AryRandom[i - 1] = k;
k++;
}
for (int j = 0; j < 30; j++)//取兩個隨機亂數做為陣列位置,並交換兩陣列中的值,以打亂依序排列的內容
{
int l, m;
int RandomNum = RandomClass.Next(0,49);
l = AryRandom[RandomNum];
l--;
int RandomNum1 = RandomClass.Next(0,49);
m = AryRandom[RandomNum1];
m--;
temp = AryRandom[l];
AryRandom[l] = AryRandom[m];
AryRandom[m] = temp;
}
for (i = 1; i < 50; i++)//將此陣列以七行七列方式呈現
{
o=i%7;
if (AryRandom[i - 1] < 10)
{
str += " " + AryRandom[i - 1] + " ";
}
else
{
str += AryRandom[i - 1] + " ";
}
if(o==0)
str +="\r\n";
}
textBox1.Text = str;
}
}
}
執行結果: