C#-如何查找数组中最常见和最不常见的整数? [英] C# - How to find the most common and the least common integers in an array?

查看:84
本文介绍了C#-如何查找数组中最常见和最不常见的整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被要求制作一个带有两个数组的骰子程序(每个骰子一个),并添加两个结果,例如:2(骰子1)+ 6(骰子2)= 8。

I was asked to make a Dice program with two arrays (one for each dice) and add the two results, e.g.: 2 (dice 1) + 6 (dice 2) = 8.

程序必须掷骰子100次并每次显示总和。
到目前为止,我可以做到,但是程序还必须显示最频繁的总和,以及最不频繁的总和。

The program must roll the dices 100 times and show the sum each time. I could do it so far, but the program also must show which sum is the most frequent, and which sum is the least frequent.

就像这样: sum = [2、2、2、2、3、3、4、4、5、6、6]。最常见:2;最少见:5。

Like this: sum = [2, 2, 2, 2, 3, 3, 4, 4, 5, 6, 6]. Most common: 2; Least common: 5.

我该怎么办?

这是我的代码的样子:

static void Main(string[] args)
    {
        Random gerador = new Random();
        int[] soma = new int[100];
        int rolagem = 0;

        for(int i = 0; i < soma.Length; i++)
        {
            rolagem = 0;
            rolagem += gerador.Next(6) + 1;
            rolagem += gerador.Next(6) + 1;
            soma[i] = rolagem;
        }

        var mais = soma.GroupBy(item => item).OrderByDescending(g => g.Count()).Select(g => g.Key).First();
        //NEED TO FIND OUT LEAST COMMON SUM

        for (int j = 1; j < soma.Length; j++)
        {
            Console.Write("{0} ", soma[j]);
        }
        Console.WriteLine("Soma mais frequente: {0}, Soma menos frequente: {1}", mais, menos);
        Console.ReadKey();
    }


推荐答案

您快到了,您可以类似地找到最不常见的一个:

You're almost there, you can find the least common one similarly:

var array = new[] { 1, 1, 1, 1, 4, 2, 2, 3, 3, 3, 5, 5 };
var result = array.GroupBy(i => i).OrderBy(g => g.Count()).Select(g => g.Key).ToList();

var mostCommon = result.Last();
var leastCommon = result.First();

这篇关于C#-如何查找数组中最常见和最不常见的整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆