直方图代码程序 [英] Histogram code program
本文介绍了直方图代码程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好.
我需要编写一个C#程序,该程序从文件中读取数字列表(int),然后输出直方图和概率列表.我能够读取该列表,但无法计算其余部分.谢谢.
这是我的代码:
Hey everyone.
I need to write a C# program that reads in a list of numbers (ints) from a file and outputs the historgram followed by the list of probabilities.I was able to to read the list but couldn''t calculate the rest. Thank you.
here is my code:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HistogramCalculator
{
class Program
{
private static int Compare(KeyValuePair<string, int> kv1, KeyValuePair<string, int> kv2)
{
return kv2.Value.CompareTo(kv1.Value); // descending order
}
public static void Main()
{
try
{
int linecount = 0;
Dictionary<string, int> histogram = new Dictionary<string, int>(); // creates a dictionary from the text file
using (StreamReader reader = new StreamReader("C:/Temp/DataImage.txt")) //reads the text file specified
{
string difline;
while ((difline = reader.ReadLine()) != null) //continues until no lines left
{
linecount++; //increases the count
if (histogram.ContainsKey(difline)) //counts specific strings
++histogram[difline];
else
histogram.Add(difline, 1);
}
}
Console.WriteLine("Line count: " + linecount);
Console.WriteLine("Max is:" + linecount);
List<KeyValuePair<string, int>> sortedHistogram = new List<KeyValuePair<string, int>>(histogram);
sortedHistogram.Sort(Compare);
foreach (KeyValuePair<string, int> kv in sortedHistogram.Take(20))
Console.WriteLine("{0}\t{1}", kv.Value, kv.Key);
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:"); // Let the user know what went wrong.
Console.WriteLine(e.Message);
}
Console.Write("\nPress any key to continue . . . ");
Console.ReadKey(true);
}
}
}
推荐答案
那么,您尝试了什么-除了真正简单的位以外?"
真的没有别的了,我的大脑僵住了,我想不起来了."
好吧.
因此,您需要将其视为一个问题,并研究如何将其分解为可运行"的位.
1)显示直方图.
1.1)控制台应用程序-因此直方图应该是一个字符序列,反映相对数字.
1.1.1)决策:直方图显示的是实际值还是相对比例? IE. 1个''*''字符代表1,最大值为1000个星号字符,或者最大值为20''*''个字符,并且该值的每1/20个为1''*''个字符?
1.1.2)决策:直方图应该是水平还是垂直?
即
"So what have you tried - other than the really simple bit?"
"nothing else really, my brain froze I can not think any more."
OK.
So, you need to look at it as a problem, and work out how to break it down into "do-able" bits.
1) Display histogram.
1.1) Console application - so histogram should be a sequence of characters, reflecting the relative numbers.
1.1.1) Decision: Is the histogram to show actual values or relative proportions? I.e. 1 ''*'' character for 1, 1000 star characters for 1000, or 20 ''*'' characters for the maximum value, and 1 ''*'' character for each 1/20 of that value?
1.1.2) Decision: Should the histogram be horizontal or vertical?
I.e.
********
***
******
**********
*
*
* *
* *
* **
* **
* **
****
****
****
交给您!
Over to you!
这篇关于直方图代码程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文