M.R M.R - 3 months ago 27
C# Question

Frequency distribution of array

Write a program that allows any number of values between 0 and 10 to be
entered. When the user stops entering values, display a frequency distribution
bar chart. Use asterisks to show the number of times each value was entered.

I wrote this:

static void Main(string[] args)
{
int numArrElement;
Console.Write("How many number do you want to enter in array: ");
numArrElement = int.Parse(Console.ReadLine());

int[] numbers = new int[numArrElement];
string inValue;

for (int i = 0; i< numArrElement; i++)
{
Console.Write("Enter your number between 0-10: ");
inValue = Console.ReadLine();
if(int.TryParse(inValue , out numbers[i]) == false)
{
Console.WriteLine("Invalid data entry----0 stored");
}
}

GetRepeatedValue(numbers);
Console.ReadKey();
}

//Method
public static void GetRepeatedValue(int[] num)
{
for (int i = 0; i < num.Length; i++)
{
int valueCnt = 0;
for (int j = 0; j < num.Length; j++)
{
if (num[j] == i)
{
valueCnt++;
}
}
if (valueCnt > 0)
{
Console.WriteLine(i + " " + valueCnt);
}
}
}

Answer
static void Main(string[] args)
{
    var data = new int[11]; //spec: valid values [0-10]

    while (true)
    {
        Console.Write("Enter a number [0-10] or 'q' to quit and draw chart: ");
        var input = Console.ReadLine();
        var value = 0;

        if (inputIsValid(input, out value))
        {
            data[value]++;
        }
        else if (input.ToLowerInvariant() == "q")
        {
            break;
        }
        else
        {
            Console.WriteLine("Invalid number, pleae try again.");
        }
    }

    Console.WriteLine();
    Console.WriteLine(printASCIIChart(data));
    Console.ReadLine();
}

private static bool inputIsValid(string input, out int value)
{
    if (int.TryParse(input, out value))
    {
        if (value > -1 && value < 11)
            return true;
    }

    return false;
}

private static string printASCIIChart(IEnumerable<int> data)
{
    var builder = new StringBuilder();
    var counter = 0;

    foreach (var num in data)
    {
        builder.AppendLine($"[{counter:00}]: {new string('*', num)}");
        counter++;
    }

    return builder.ToString();
}

The relevant part is printASCIIChart and the way to store the user's input.

The easiest way to store the data is simply using an array that keeps count of each number incrementing the counter in the corresponding index. Printing out the bar chart is pretty straighforward once your data is stored this way, simply using this handy string constructor.

Comments