Как я могу сделать гистограмму в c#? - PullRequest
0 голосов
/ 10 апреля 2020

Итак, мой учитель хочет, чтобы мы составили диаграмму, которая подсчитывает, сколько слов повторяется в строке, и отображает примерно так: я (диаграмма здесь) 12 меня (диаграмма здесь) 2 вы, ребята, понимаете, но он хочет, чтобы мы сделайте это с Console.Bacground / Forground Color, но он никогда не объяснял, как или давал какие-либо инструкции о том, как, поэтому я понятия не имею, он сказал, что нам нужно al oop, но я сделал это и не работал, только раскрасил слова

foreach (KeyValuePair<string, int> kvp in RepeatedWordCount)
{
    Console.BackgroundColor = ConsoleColor.White;
    Console.WriteLine("\n");
    Console.WriteLine(kvp.Key + kvp.Value);
} 

Пожалуйста, помогите и спасибо <3 </p>

1 Ответ

0 голосов
/ 10 апреля 2020

Горизонтальная гистограмма

Горизонтальная диаграмма будет проще всего для этого, когда мы отображаем значения по горизонтали и ключи (слова) по вертикали, потому что у нас есть «неограниченное» вертикальное пространство и там вероятно, будет много слов для отображения данных.

Также проще создать такой график, поскольку мы записываем все данные для одного слова в одну строку. Мы могли бы сделать вертикальную диаграмму, но это было бы немного хитрее.

Я бы сделал что-то вроде этого:

  1. Во всех oop, для Для каждого элемента напишите слово и добавьте слева от него пробелы, чтобы у нас было четное левое поле для графа
  2. Напишите строку из символов, представляющих количество экземпляров слова

Например:

// Populate some random word counts for an example
var RepeatedWordCount = new Dictionary<string, int>
{
    {"the", 20}, {"you", 13}, {"was", 9}, {"as", 5},
    {"a", 17}, {"in", 15}, {"I", 1}, {"he", 10},
    {"they", 2}, {"of", 19}, {"on", 7}, {"that", 12},
    {"his", 3}, {"it", 11}, {"to", 16}, {"for", 8},
    {"are", 6}, {"with", 4}, {"is", 14}, {"and", 18},
};

// Get the length of the longest word so we can pad all
// words to the same length and have an even margin
var maxWordLength = RepeatedWordCount.Keys.Max(k => k.Length);

// Create some colors to differentiate the bars
var colors = new[]
{
    ConsoleColor.Red, ConsoleColor.DarkBlue, ConsoleColor.Green,
    ConsoleColor.DarkYellow, ConsoleColor.Cyan, ConsoleColor.DarkMagenta,
    ConsoleColor.DarkRed, ConsoleColor.Blue, ConsoleColor.DarkGreen,
    ConsoleColor.Yellow, ConsoleColor.DarkCyan, ConsoleColor.Magenta,
};

var colorIndex = 0;

foreach (KeyValuePair<string, int> kvp in RepeatedWordCount)
{
    // Write the word and vertical line
    Console.Write(kvp.Key.PadLeft(maxWordLength + 2, ' ') + " | ");

    // Write the chart value using the next color in the array
    Console.ForegroundColor = colors[colorIndex++ % colors.Length];
    Console.WriteLine(new string('█', kvp.Value));
    Console.ResetColor();
}

Console.Write("\nDone! Press any key to exit...");
Console.ReadKey();

Пример вывода

enter image description here


Вертикальная гистограмма

Теперь, когда мы видим, как сделать горизонтальный график, мы можем подумать о том, как сделать вертикальный график. В этом случае нам нужно знать значения для каждой строки, а затем, начиная с верхней части диаграммы, где «строка» является максимальным значением, записать блок solid для каждой строки, значение которой равно или больше значения текущей строки.

В нижней части диаграммы нам нужно написать каждое слово вертикально, поэтому нам нужно написать по одному символу на строку для каждого.

Возможно, какой-то код более нагляден:

// Populate some random word counts for an example
var RepeatedWordCount = new Dictionary<string, int>
{
    {"the", 20}, {"you", 13}, {"was", 9}, {"as", 5},
    {"a", 17}, {"in", 15}, {"I", 1}, { "he", 10},
    {"they", 2}, {"of", 19}, {"on", 7}, {"that", 12},
    {"his", 3}, {"it", 11}, {"to", 16}, {"for", 8},
    {"are", 6}, {"with", 4}, {"is", 14}, {"and", 18},
};

// Get the count value for the word with the highest count
var maxWordCount = RepeatedWordCount.Values.Max();

// Create some colors to differentiate the bars
var colors = new[]
{
    ConsoleColor.Red, ConsoleColor.DarkBlue, ConsoleColor.Green,
    ConsoleColor.DarkYellow, ConsoleColor.Cyan, ConsoleColor.DarkMagenta,
    ConsoleColor.DarkRed, ConsoleColor.Blue, ConsoleColor.DarkGreen,
    ConsoleColor.Yellow, ConsoleColor.DarkCyan, ConsoleColor.Magenta,
};

Console.WriteLine();

// Get all the counts
var values = RepeatedWordCount.Values.ToList();

// Start at the top of the chart, where the value is maxWordCount
// and work our way down, writing a block for each string that
// has a value greater than or equal to the count for that row
for (int i = maxWordCount; i > 0; i--)
{
    for (int j = 0; j < RepeatedWordCount.Count; j++)
    {
        Console.ForegroundColor = colors[j % colors.Length];
        Console.Write(values[j] >= i ? "███" : "   ");
        Console.ResetColor();
    }

    Console.WriteLine();
}

// Write each word vertically below it's line
var words = RepeatedWordCount.Keys.ToList();
var maxWordLength = words.Max(w => w.Length);

for (var i = 0; i < maxWordLength; i++)
{
    foreach (var word in words)
    {
        Console.Write(word.Length > i ? $" {word[i]} " : "   ");
    }

    Console.WriteLine();
}

Console.Write("\nDone! Press any key to exit...");
Console.ReadKey();

Пример вывода

enter image description here

...