如果2D阵列仅作为帮助您打印的工具,则可以将其完全保留.
private static readonly char GraphBackgroundChar = '0'; private static readonly char GraphBarChar = '1'; void Main() { int[] input = {4, 1, 6, 2}; int graphHeight = input.Max(); // using System.Linq; for (int currentHeight = graphHeight - 1; currentHeight >= 0; currentHeight--) { OutputLayer(input, currentHeight); } } private static void OutputLayer(int[] input, int currentLevel) { foreach (int value in input) { // We're currently printing the vertical level `currentLevel`. // Is this value's bar high enough to be shown on this height? char c = currentLevel >= value ? GraphBackgroundChar : GraphBarChar; Console.Write(c); } Console.WriteLine(); }
这基本上做的是它从输入中找到"最高条",然后从上到下遍历每个垂直级别,GraphBarChar
每当图形条在input
当前高度可见时打印.
一些样品:
input = {2,1,3};
001 101 111
input = {2,4,1,0,3};
01000 01001 11001 11101
如果您的目标平台支持终端仿真器中的框绘制字符,则可以使用以下字符表示一些非常有说服力的条形图:
private static readonly char GraphBackgroundChar = '?'; private static readonly char GraphBarChar = '?';
input = {2,1,3};
??? ??? ???
input = {2,4,1,0,3};
????? ????? ????? ?????