【问题标题】:List of how many times a number appeared in an array [duplicate]一个数字在数组中出现的次数列表[重复]
【发布时间】:2017-04-21 19:12:22
【问题描述】:

我必须创建一个由 n 个元素组成的数组,并找出 每个 数字出现的次数,如下所示:

Array: (-1.7 ; 3.0 ; 0.0 ; 1.5 ; 0.0 ; -1.7 ; 2.3 ; -1,7)
-1.7 appears 3 times
 3.0 appears 1 time
 0.0 appears 2 times
 1.5 appears 1 time
 2.3 appears 1 time

我试过了,我的代码是这样的:

        int n = 0;
        Console.WriteLine("Type in the size of your array...");
        n = int.Parse(Console.ReadLine());

        float[] vet = new float[n];
        int[] freq = new int[n];

        Console.WriteLine("Now, type in each element...");
        for(int i = 0; i < vet.Length; i++)
        {
            Console.Write("Position {0}: ", i);
            vet[i] = float.Parse(Console.ReadLine());
        }
        for(int j = 0; j< vet.Length; j++)
        {
            for(int k = 0; k< freq.Length; k++)
            {
                if(vet[j] == vet[k])
                {
                    freq[j]++;
                }
            }
        }
        Console.WriteLine("The number of times each element appears in the array is:");

        for(int l = 0; l< freq.Length; l++)
        {
            Console.WriteLine("{0} appears {1} time(s)", vet[l], freq[l]);
        }
        Console.ReadKey();

但是输出还是这样的:

The number of times each element appears in the array is:
-1.7 appears 3 time(s)
 3.0 appears 1 time(s)
 0.0 appears 2 time(s)
 1.5 appears 1 time(s)
 0.0 appears 2 time(s)
-1.7 appears 3 time(s)
 2.3 appears 1 time(s)
-1.7 appears 3 time(s)

我的问题是:我怎样才能让我的代码像第一个示例一样以打印一次重复数字的方式工作?

【问题讨论】:

标签: c# arrays


【解决方案1】:

尝试改用Dictionary。代码如下:

    var arr = new double [] { -1.7, 3.0, 0.0, 1.5, 0.0, -1.7, 2.3, -1.7 };
    var dic = new Dictionary<double, int>();

    foreach (var element in arr)
    {
        if (dic.ContainsKey(element))
            dic[element]++;
        else
            dic[element] = 1;
    }

    foreach (var element in dic)
    {
        Console.WriteLine(element.Key + " appears " + element.Value + " time(s)");
    }

【讨论】:

    【解决方案2】:

    我个人会像这样使用 linq:

        decimal[] values = {-1.7m , 3.0m , 0.0m , 1.5m , 0.0m , -1.7m , 2.3m , -1,7m};
        
        var result = values
            .GroupBy(v => v)
            .ToDictionary(g => g.Key, g => g.Count());
        
        foreach(var kvp in result)
        {
            Console.WriteLine("{0} appears {1} time(s)", kvp.Key, kvp.Value);
        }
    

    DotNetFiddle.Net

    结果:

    -1.7 出现 2 次​​p>

    3.0 出现 1 次

    0.0 出现 2 次​​p>

    1.5 出现 1 次

    2.3 出现 1 次

    -1 出现 1 次

    7 出现 1 次

    【讨论】:

    • 但是 -1.7 出现了 3 次而不是 2 次。而且 -1 和 7 根本不在列表中。
    • 对不起,您的小数可能有误...其中一些是-1.7,另一些是-1,7 将-1 和7 变成两个单独的数字。不过谢谢!
    • 我明白为什么,最后一个条目是 -1,7 而不是 -1.7。看起来代码很好,他只是通过错误输入源数组而弄乱了结果。
    • 我想避免使用Linq,因为我的老师不希望我们使用它......但我认为这是不可避免的。谢谢!
    • @RuneHobbo 这是可以避免的,你应该听听老师告诉你的。
    【解决方案3】:

    非非非非非。您没有使用 C# 的强大功能。这也可能是一个 c++ 程序。更好的方法是使用类似的方法将数组转换为列表

    List<float> list=vet.ToList()
    

    那么你可以关注这里的信息:Get a list of distinct items and their count

    我会写在这里:

    var query = list.SelectMany(x => x.Names)
                .GroupBy(s => s)
                .Select(g => new { Name = g.Key, Count = g.Count() });
    
    foreach(var result in query) {
        Console.WriteLine("Name: {0}, Count: {1}", result.Name, result.Count);
    }
    

    【讨论】:

    • 对不起!我还是个学生,也是初学者。我对 Linq 完全不了解,但是这个答案很有帮助,谢谢!
    【解决方案4】:

    典型的解决方案是基于Linq

    using System.Linq;
    
    ...
    
    var freqs = vet
      .GroupBy(item => item)
      .OrderBy(chunk => chunk.Key)
      .Select(chunk => 
         $"{chunk.Key,4:f1} appears {chunk.Count()} {(chunk.Count() > 1 ? "times" : "time")}");
    
    Console.WriteLine("The number of times each element appears in the array is:");
    
    Console.Write(string.Join(Environment.NewLine, freqs));
    
    Console.ReadKey();
    

    结果:

    The number of times each element appears in the array is:
    -1.7 appears 3 times
     0.0 appears 2 times
     1.5 appears 1 time
     2.3 appears 1 time
     3.0 appears 1 time
    

    【讨论】:

      猜你喜欢
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      • 1970-01-01
      • 2023-01-20
      相关资源
      最近更新 更多