4 用c# 产生一个 int 数组 长度为100,并向其中随机插入 1-100 ,并且不能重复

对上面生成的数组升序排序
2024-12-16 18:12:18
推荐回答(3个)
回答1:

添加了直接运行:
class getRandowArray
{
public getRandowArray()
{
arr = new int[100];
}
int[] arr;

///


/// 检查数组中是否已存在此数
///

/// ture为已存在
private bool checkNumber(int arrlist)
{
for (int i = 0; i < arrlist; ++i)
{
if (arr[i] == arr[arrlist])
return true;
}
return false;
}

///
/// 生成数组
///

/// 数组
public int[] produceRandomArray()
{
Random rd=new Random();
for (int i = 0; i < 100; ++i)
{
//int temp=0;

do
{
//temp = rd.Next(1, 101);
//arr[i] = temp;
arr[i] = rd.Next(1, 101);
}
while (checkNumber(i));
}
return arr;
}
}
class Program
{

static void Main(string[] args)
{
getRandowArray produceArr = new getRandowArray();
int[] arr = produceArr.produceRandomArray();
for (int i = 0; i < arr.Length; ++i)
{
Console.WriteLine(arr[i]);
}
}
}

回答2:

int[] yourArray=new int[100];
ArrayList myList=new ArrayList();
Random rnd=new Random();
while(myList.Count<100)
{
int num=rnd.Next(1,101);
if(!myList.Contains(num))
myList.Add(num);
}
for(int i=0;i<100;i++)
yourArray[i]=(int)myList[i];

for(int i=yourArray.length-1;i>=0;i--)
{
for(int j=0;j if(yourArray[j]>yourArray[j+1]){
int temp=yourArray[j];
yourArray[j]=yourArray[j+1];
yourArray[j+1]=temp;}
}
}

回答3:

public static int[] getArr(int len){
int[] arr=new int[len];
System.Collections.ArrayList list=new System.Collections.ArrayList(len);
Random rnd=new Random();
int next;
for(int i=0;iwhile(list.Contains(next=rnd.Next(1,len+1))){
}
list.Add(next);
arr[i]=next;
}
return arr;
}