排行榜与不同的列表
本文关键字:列表 排行榜 | 更新日期: 2023-09-27 18:14:48
我只是想知道,根据这个规则(一个单词中不同的字母)^2/(单词中的总字母)什么是最好的单词。所以我从一些基本的东西开始
StreamReader SR = new StreamReader (FILE_PATH);
int counter = 0;
string line;
List<string> words = new List<string> ();
List<double> points = new List<double> ();
while ((line = SR.ReadLine ()) != null) {
short unique = (short)line.Distinct ().ToArray ().Length;
short total = (short)line.Length;
double value = (15 * Math.PI * Math.Pow (unique, 2)) / total;
words.Add (line);
points.Add (value);
counter++;
}
int Index = points.IndexOf (points.Max ());
Console.WriteLine ("best: " + words [Index] + " points: " + points [Index]);
}
但是我也想要一个包含"最佳"单词和相对分数的排行榜。我有一个想法,需要不同的列表来找出有点的单词,但有没有更简单、更快速的方法?
我建议使用单个 Dictionary<string, double>
(word及其对应的值)而不是两个压缩的Lists
:
Dictionary<string, double> points = File
.ReadLines(FILE_PATH)
//.Where(line => !string.IsNullOrEmpty(line)) // you may want to filter out empty lines
.Select(line => new {
word = line,
unique = word.Distinct().Count()
total = word.Length })
.ToDictionary(item => item.word,
item => 15 * Math.PI * item.unique * item.unique / item.total);
所以你可以很容易地实现一个排行榜与帮助Linq:
var TopTen = points
.OrderByDescending(pair => pair.Value)
.ThenBy(pair => pair.Key)
.Take(10)
.Select(pair => $"word: {pair.Key} points: {pair.Value}");
Console.Write(String.Join(Environment.NewLine, TopTen));