Reputation: 13
I know this has been asked numerous times before, but I could not find what specifically I 'm looking for.
I'm currently trying to write c# method that displays int array as vertical bars on console. My idea is to transform 1D array into 2D.
if input = {2, 1, 3}
; Output should look like:
{{0, 0, 1},
{1, 0, 1},
{1, 1, 1}}
Then I could replace 1 and 0 by character of my choice to display the image on the console. So far my method looks like this:
public static void DrawGraph()
{
int[] randomArray = new int[3]{ 2, 1, 3 };
int[,] graphMap = new int[3, 3];
for(int i = 0; i < graphMap.GetLength(0); i++)
{
for(int j = 0; j < graphMap.GetLength(1); j++)
{
graphMap[i, j] = randomArray[j];
Console.Write(graphMap[i, j]);
}
Console.WriteLine();
}
}
And it produces output:
2 1 3
2 1 3
2 1 3
Upvotes: 1
Views: 1124
Reputation: 680
Here is a better function than the one given already,
static void DrawGraph(int[] array)
{
int maxElementValue = 0;
foreach (int i in array)
{
if (i > maxElementValue) maxElementValue = i;
}
for (int rowIndex= 0; rowIndex < maxElementValue; ++rowIndex)
{
foreach (int i in array)
{
Console.Write((i < rowIndex - columnIndex ? 0 : 1) + " ");
}
Console.WriteLine();
}
}
It works as desired.
Upvotes: 0
Reputation: 13662
If the 2D array is only relevant as a tool to help you print, you can leave it out completely.
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();
}
What this basically does is it finds the "highest bar" from the input, then loops through each vertical level top-to-bottom, printing GraphBarChar
each time a graph bar in input
is visible at the current height.
Some samples:
input = {2, 1, 3};
001
101
111
input = {2, 4, 1, 0, 3};
01000
01001
11001
11101
If your targeted platforms support box-drawing characters in the terminal emulators, you could use the following characters for some pretty convincing bar graphs:
private static readonly char GraphBackgroundChar = '░';
private static readonly char GraphBarChar = '█';
input = {2, 1, 3};
░░█
█░█
███
input = {2, 4, 1, 0, 3};
░█░░░
░█░░█
██░░█
███░█
Upvotes: 5