我是C#的初学者。我的任务是用随机生成的数字填充数组并检查是否有相似的数字并用新的随机数更改它们。 但是应该根据现有数组检查这个新生成的随机数。 我需要帮助完成上一个任务。
这是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
Random r = new Random();
int[] x = new int[20];
for (int i=0; i < 20; i++)
{
x[i] = r.Next(100);
Console.Write(x[i]+" "); //printing original array
}
Console.WriteLine();
Console.WriteLine("New array is : ");
for (int k = 0; k < 20;k++ )
{
for (int n = k + 1; n < 20;n++ )
{
if (x[n]==x[k]) //checking if there duplicated ones
{
Console.Write("New number is: ");
x[k]= r.Next(100);
}
}
Console.WriteLine(x[k]);
}
Console.ReadKey();
}
}
}
提前谢谢
答案 0 :(得分:2)
不需要那种长计算,你可以简单地在开头做一个while循环来创建随机数,直到数组不包含像创建的那样的数字,如下所示:
Random r = new Random();
int[] x = new int[20];
for (int i = 0; i < x.Length; i++)
{
do
{
x[i] = r.Next(100);
} while (x.Contains(x[i])); // loops until the array does not contain an number like the one that was just created
Console.Write(x[i] + " ");
}
或者如果你想继续按照自己的方式去做,而不是编写嵌套for循环,你可以用array.Contains(element)方法创建一个只有一个条件的循环。如果有一个与括号中给出的元素相同的元素,则此方法返回true;如果没有,则返回false。
答案 1 :(得分:1)
@Lynx答案完美无缺,但我想提供一个不使用LINQ的替代方案:x.Contains(...)
static void Main(string[] args)
{
Random r = new Random();
int[] x = new int[20];
for (int i = 0; i < 20; i++)
{
x[i] = r.Next(100);
Console.Write(x[i] + " ");
}
Console.WriteLine("New array is : ");
for (int k = 0; k < 20; k++)
{
for (int n = k + 1; n < 20; n++)
{
if (x[n] == x[k])
{
int newNumber;
//Keeps generating a number which doesnt exists
//in the array already
do
{
newNumber = r.Next();
} while (contains(x, newNumber));
//Done generating a new number.
Console.Write("New number is: ");
x[k] = newNumber;
}
}
Console.WriteLine(x[k]);
}
}
/// <summary>
/// Returns true if the given array contains the given number
/// </summary>
/// <param name="array">The array to check</param>
/// <param name="number">The number to check</param>
/// <returns>bool True if number exists in array</returns>
static bool contains(int[] array, int number)
{
for (int i = 0; i < array.Length; i++)
{
if (array[i] == number)
{
return true; //Returns true if number already exists
}
}
return false;
}