[Solved] Frequency distribution of array [closed]


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.

solved Frequency distribution of array [closed]