【问题标题】:Which number occurs the most frequently and how many times it occurs [closed]哪个数字出现得最频繁​​以及它出现了多少次[关闭]
【发布时间】:2022-02-18 18:57:01
【问题描述】:

我是 C# 的新手,我想知道更有经验的程序员如何解决这个问题。在这段代码中,它是一个带有一堆数字和字母的私有 const 字符串。我需要我的程序找出最常出现的数字以及出现的次数并吐出结果。

public class Program
{
private const string FileContents = "\"12345.56789\",\"12345.56789\",\"12345.56789\",\"12345.56789\"";
public static void Main()
{
}
}

【问题讨论】:

  • 你认为这里的“数字”是什么?个位数?还是 \" 和 \" 之间的全部内容?

标签: c#


【解决方案1】:

您可以在每个数字/单词上使用GroupBy,然后检查每个组中元素的计数,

private const string FileContents = "\"12345.56789\",\"12345.56789\",\"12345.56789\",\"12345.56789\"";
var mostFrequent = FileContents
    .Split(',')
    .GroupBy(x => x)
    .Select(x => new {Key = x.Key, Count = x.Count()})
    .OrderByDescending(x => x.Count)
    .FirstOrDefault();

mostFrequent 变量将包含给定const 字符串中出现次数最多的数字或单词(字母)。


如果你只想要数字而不是单词,那么你必须将拆分数组过滤成数字数组,如下所示

var mostFrequentNumber = FileContents
    .Split(',')
    .Select(x => x.Trim("\""))  //Remove leading and trailing \"
    .Where(x => float.TryParse(x, out _)) //Check string is numeric or not
    .GroupBy(x => x)
    .Select(x => new {Key = x.Key, Count = x.Count()})
    .OrderByDescending(x => x.Count)
    .FirstOrDefault();

【讨论】:

  • 你可以使用.Where(x => char.IsDigit(x)) 而不是.Split(",") .Select(x => x.Trim("\"")) //Remove leading and trailing \" .Where(x => float.TryParse(x, out float number))
  • "," 的引号必须是单引号:',' 是字符而不是字符串(对于 "\"")。你可以在这里使用discardfloat.TryParse(x, out _)。并且在FirstOrDefault() 之前缺少点。
  • @AndrewMorton。感谢您的评论,我修复了您指出的问题并使用了我不知道的丢弃。感谢您的链接。
  • @valentin,我们不能使用.Where(x => char.IsDigit(x)),因为数字本质上是十进制的。它包含十进制数
  • @valentin,如果你有比我更好的方法,我很高兴看到它
【解决方案2】:

您可以按照以下步骤进行操作:

  1. 将字符串解析为数字集合
  2. 组编号(组应包含编号本身及其出现次数)
  3. 按出现次数对组进行排序(按降序排列)并取第一个(因此出现次数最多的组)
  4. 从组中提取号码

【讨论】:

    猜你喜欢
    • 2015-03-25
    • 2022-11-28
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-14
    • 2011-11-18
    • 2013-12-09
    相关资源
    最近更新 更多