提问人:Sabotenderizer 提问时间:4/7/2013 最后编辑:Sabotenderizer 更新时间:2/13/2023 访问量:73736
计算值在数组中出现的次数
Counting the number of times a value appears in an array
问:
那么,在 C# 中创建循环的好而简单的算法是什么,每次某个值出现在数组中时,它都会将 1 添加到另一个数组中的计数器中?
例如,我有这个:
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]);
}
}
}
}
我只计算数字数组中出现 4 个数字的次数。有人建议我在第一个循环中使用该方法,但它似乎不起作用,并产生了一个错误,即数组中的索引越界。我想显示这些数字(5、7、9 和 1)中每个数字在 4 行中出现的次数。
编辑:不使用LINQ或任何其他花哨的东西,如字典或其他任何东西。
答:
用于完成工作LINQ
using System.Linq;
var numQuery =
from num in numbers
where num == 5
select num;
Console.WriteLine("Count of 5: " + numQuery.Count);
或者使用method syntax
var numQuery = numbers.Where(num => num == 5);
Console.WriteLine("Count of 5: " + numQuery.Count);
有关概述,请参阅此处,有关-syntax,请参阅此处。
找到 的样本,请看这里。query vs method
GroupBy
评论
GroupBy
您的 count 数组有 4 个字段 ...
一个索引为 0、1、2 和 3
那么,如果像 4(或更大)这样的数字碰巧被计算在内会发生什么?YOR 代码尝试访问索引 4 ...不存在......
评论
由于此部分,您收到索引越界错误:
for (i = 0; i < SIZE - 1; i++)
{
if (numbers[i] > 0 && numbers[i] < SIZE)
{
x = Count[i];
请注意,当只有 .0
SIZE - 1
11
Count
4
不过,使用 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());
因此,它按数字的值对数字进行分组,然后我们将列表细化为仅包含 4 组,然后选择每个组中的第一个,留下一个 s 的集合。int
下面是一个非基于 LINQ 的解决方案,它使用 Dictionary 来存储数字计数。
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);
}
}
通过对程序进行一些修改,您可以获得一些结果。
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);
}
输出:
7
9
评论
Console.WriteLine("{0}", Count[i]);
if (Count[i] == 4)
Console.WriteLine("{0}: {1}", i, Count[i]);
我使用正则表达式作为我的解决方案,因为我只有三个值。
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;
看起来很“骇人听闻”,但对我有用。它可以处理字符串或数字,但前提是您正在处理几个值。在这种情况下非常有效。如果没有,我认为另一个答案会是一个更好的选择。
评论
这是查找“计算值在数组中出现的次数”的幼稚解决方案 想法:在数组中构建哈希映射 溶液:
using System.Collections.Generic;
using System.Text;
namespace GetArrEleFrequency
{
class Program
{
static int[] Arr = new int[5] { 3, 3, 0, 2, 0 };
static int[] Key = new int[5];
static int[] value = new int[5];
static void Main(string[] args)
{
int keyItr = -1, ValueItr = -1, tempIndex = 0, tempValue = 0;
for (int i=0; i <= Arr.Length-1;i++) {
if (!(isPresent(Arr[i]))) {
keyItr += 1;ValueItr += 1;
Key[keyItr] = Arr[i];
value[ValueItr] = 1;
} else {
value[tempIndex] = value[getIndex(Arr[i])] + 1;
}
}
for (int i=0;i<=Key.Length-1;i++) {
Console.WriteLine(Key[i] + "-" + value[i]);
}
Console.ReadKey();
}
public static Boolean isPresent(int num) {
Boolean temp = false;
for (int i=0; i <= Key.Length-1;i++) {
if (Key[i] == num) {
temp = true;
break;
} else {
temp = false;
}
}
return temp;
}
public static int getIndex(int num) {
int temp = 0;
for (int i=0;i<=Key.Length-1;i++) {
if (Key[i] == num) {
break;
} else {
temp += 1;
}
}
return temp;
}
}
}
Output :
3 - 2
0 - 2
2 - 1
0 - 0
0 - 0
static void Main(string[] args)
{
int[] arr = new int[] { 45, 34, 23, 67, 10, 99,99,10 };
foreach(int i in arr.Distinct())
{
int count = occurance(arr,i);
Console.WriteLine(i + "-Occurred For :" + count);
}
Console.ReadLine();
}
public static int occurance(int[] arr,int x)
{
int count = 0;
foreach(int num in arr)
{
if(x==num)
{
count++;
}
}
return count;
}
}
我认为如果不使用列表、LINQ 或字典,这个问题就无法得到回答,所以这是我的建议:
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
class Program
{
static void Main()
{
int n = int.Parse(Console.ReadLine()); // the size of the array
int[] ints = new int[n]; //an array to store the items, integers in this case
int[] freq = new int[n]; //an array to store the frequency of each element with the same index
for (int i = 0; i < n; i++) // a loop that takes each element on a new row
{
ints[i] = int.Parse(Console.ReadLine());
}
for (int j = 0; j < n; j++) // loops to iterate through the ints array and pick up the
// frequencies and store them in the freq array
{
for (int k = 0; k < n; k++)
{
if (ints[j] == ints[k] && k != n)
{
freq[j]++;
}
}
}
int indexAtMax = freq.ToList().IndexOf(freq.Max()); //this picks up the index of the first maximum count
int mostFrequentNumber = ints[indexAtMax]; // the actual number behind the same inex in the ints array
int frequencyOfRepeating = freq[indexAtMax]; // the actual number of the frequency
Console.WriteLine($"The most frequent number is:{mostFrequentNumber} and it repeats {frequencyOfRepeating} times)");
}
}
评论