C# 计算一个值在数组中出现的次数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15862191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Counting the number of times a value appears in an array
提问by Sabotenderizer
So what's a good, simple algorithm to create a loop in C# where every time a certain value appears in an array it adds 1 to a counter in another array?
那么在 C# 中创建一个循环的好的简单算法是什么,每次某个值出现在数组中时,它都会将 1 添加到另一个数组中的计数器?
For example I have this:
例如我有这个:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication22
{
class Program
{
const int SIZE = 12;
static void Main(string[] args)
{
int[] numbers = new int[SIZE] {5, 5, 5, 7, 7, 7, 9, 7, 9, 9, 9, 1};
string[] letters = new string[SIZE] { "m", "m", "s", "m", "s", "s", "s", "m", "s", "s", "s", "s" };
int[] values = new int[SIZE] {15, 22, 67, 45, 12, 21, 24, 51, 90, 60, 50, 44};
string[] status = new string[SIZE] { "f", "m", "f", "a", "m", "f", "f", "f", "m", "f", "m", "f" };
int[] Count = new int[4];
int x = 0;
int i = 0;
for (i = 0; i < SIZE - 1; i++)
{
if (numbers[i] > 0 && numbers[i] < SIZE)
{
x = Count[i];
Count[x]++;
}
}
for (i = 0; i < 4; i++)
{
Console.WriteLine("{0}", Count[4]);
}
}
}
}
I am only counting the number of times 4 numbers appear in the numbers array. Someone suggested I use the method in the first loop but it doesn't seem to be working and creates an error that the index is out of bounds in the array. I want to display the number of times each of those numbers(5, 7,9 and 1) appear in 4 rows.
我只计算数字数组中出现 4 个数字的次数。有人建议我在第一个循环中使用该方法,但它似乎不起作用,并创建了索引超出数组范围的错误。我想显示每个数字(5、7、9 和 1)出现在 4 行中的次数。
EDIT: Without using LINQ or any other fancy thing like Dictionary or whatever.
编辑:不使用 LINQ 或任何其他花哨的东西,如字典或其他任何东西。
采纳答案by Daniel Imms
You're getting an index out of bounds error because of this section:
由于此部分,您收到索引越界错误:
for (i = 0; i < SIZE - 1; i++)
{
if (numbers[i] > 0 && numbers[i] < SIZE)
{
x = Count[i];
Notice that you're iterating through 0
to SIZE - 1
(11
) when Count
only has a size of 4
.
请注意,您是通过迭代0
到SIZE - 1
(11
)时,Count
只有一个尺寸4
。
You can do this task pretty easily with LINQ though.
不过,您可以使用 LINQ 轻松完成此任务。
int[] numbers = new int[SIZE] { 5, 5, 5, 7, 7, 7, 9, 7, 9, 9, 9, 1 };
var count = numbers
.GroupBy(e => e)
.Where(e => e.Count() == 4)
.Select(e => e.First());
So it groups the numbers by their value, we then refine the list to only include groups of 4, then select the first of each to be left with a collection of int
s.
因此它按数值对数字进行分组,然后我们将列表细化为仅包含 4 组,然后选择每个组中的第一个以留下int
s的集合。
Here is a non-LINQ based solution using a Dictionary to store the count of numbers.
这是一个基于非 LINQ 的解决方案,使用字典来存储数字计数。
int[] numbers = new int[SIZE] { 5, 5, 5, 7, 7, 7, 9, 7, 9, 9, 9, 1 };
var dictionary = new Dictionary<int, int>();
var numbersWithFour = new List<int>();
foreach (var number in numbers)
{
if (dictionary.ContainsKey(number))
dictionary[number]++;
else
dictionary.Add(number, 1);
}
foreach (var val in dictionary)
{
if (val.Value == 4)
{
numbersWithFour.Add(val.Key);
}
}
With a little modification to your program you can get some results.
对您的程序稍作修改,您就可以获得一些结果。
int[] numbers = new int[SIZE] { 5, 5, 5, 7, 7, 7, 9, 7, 9, 9, 9, 1 };
string[] letters = new string[SIZE] { "m", "m", "s", "m", "s", "s", "s", "m", "s", "s", "s", "s" };
int[] values = new int[SIZE] { 15, 22, 67, 45, 12, 21, 24, 51, 90, 60, 50, 44 };
string[] status = new string[SIZE] { "f", "m", "f", "a", "m", "f", "f", "f", "m", "f", "m", "f" };
// Set the size of Count to maximum value in numbers + 1
int[] Count = new int[9 + 1];
int x = 0;
int i = 0;
for (i = 0; i < SIZE - 1; i++)
{
if (numbers[i] > 0 && numbers[i] < SIZE)
{
// Use value from numbers as the index for Count and increment the count
Count[numbers[i]]++;
}
}
for (i = 0; i < Count.Length; i++)
{
// Check all values in Count, printing the ones where the count is 4
if (Count[i] == 4)
Console.WriteLine("{0}", i);
}
Output:
输出:
7
9
回答by bash.d
Use LINQ
to do the work
使用LINQ
做的工作
using System.Linq;
var numQuery =
from num in numbers
where num == 5
select num;
Console.WriteLine("Count of 5: " + numQuery.Count);
Or use the method syntax
或者使用 method syntax
var numQuery = numbers.Where(num => num == 5);
Console.WriteLine("Count of 5: " + numQuery.Count);
See herefor the overview and herefor query vs method
-syntax.
Found a sample for GroupBy
, look here.
回答by DarkSquirrel42
your count array has 4 fields ...
您的计数数组有 4 个字段...
one with the index 0, 1, 2 and 3
一个索引为 0、1、2 和 3
so what will happen if a number like 4 (or greater) happens to be counted? yor code tries to access index 4 ... which does not exist ...
那么,如果碰巧计算出像 4(或更大)这样的数字会发生什么?您的代码尝试访问不存在的索引 4 ...
回答by ykadaru
I used Regex for my solution since I only had three values.
我使用 Regex 作为我的解决方案,因为我只有三个值。
String results = "" + one.ToString() + " " + two.ToString() + " " + three.ToString();
int count1 = Regex.Matches(results, @one.ToString()).Count;
int count2 = Regex.Matches(results, @two.ToString()).Count;
int count3 = Regex.Matches(results, @three.ToString()).Count;
Seems 'hacky', but worked for me. It'll work with strings or numbers but only if you're working with a few values. Pretty efficient in that case. If not, I think the other answer would be a better option.
似乎“hacky”,但对我有用。它适用于字符串或数字,但前提是您使用的是几个值。在这种情况下非常有效。如果没有,我认为另一个答案将是更好的选择。