我有一个随机数组,我必须搜索整数在数组中的次数。这就是我已经拥有的。你会如何搜索结果数组?
Console.WriteLine("enter number:");
int number = Convert.ToInt32(Console.ReadLine());
int[] array = new int[number];
Random rnd = new Random();
for ( int i = 0; i < array.Length; i++)
{
array[i] = rnd.Next(0 , number);
}
foreach (int i in array)
{
System.Console.Write(" {0}",i);
}
Console.ReadKey();
答案 0 :(得分:2)
foreach(var g in array.GroupBy(x=>x))
{
Console.WriteLine("{0} Count:{1}",g.Key,g.Count())
}
答案 1 :(得分:2)
其他答案依赖于LINQ,这是使用普通C#
执行此操作的代码int count = 0;
foreach (int i in array)
{
if (i == number)
count = count + 1;
}
请注意,在现有代码中,这将始终生成0
,因为Random.Next()
的上限是独占的。您应该将代码更改为此类型,其中输入的数字未链接到您生成的数组:
int array_size = 1000;
int max_number = 100;
int[] array = new int[array_size];
Random rnd = new Random();
for (int i = 0; i < array.Length; i++)
array[i] = rnd.Next(0, max_number);
Console.WriteLine("enter number:");
int number = Convert.ToInt32(Console.ReadLine());
foreach (int i in array)
System.Console.Write("{0} ", i);
int count = 0;
foreach (int i in array)
if (i == number)
count = count + 1;
Console.WriteLine("Number {0} was found {1} times in the array", number, count);
Console.ReadKey();