{ }codelper
filled listscountingP0150

Vertical survey histogram

A satisfaction survey asked people to choose a score from 1 to k, and n answers were collected.
The first line gives n and k, and the second line gives the n answers separated by single spaces.
Answers outside 1 to k are invalid and are left out of the chart.
Count the answers for each score and print a vertical bar chart.
Let H be the largest count; the bar rows are the H rows for heights H down to 1, printed from the top row (height H).
Each bar row has k characters, and the j-th character is '#' if the count for score j is at least that row's height, otherwise '.'.
After the bar rows print the score row "12...k" (the digits 1 to k joined without spaces).
On the last line print the number of invalid answers.
If there is no valid answer, H is 0 and no bar rows are printed.

Input
1 ≤ n ≤ 1000, 1 ≤ k ≤ 9, 0 ≤ answer ≤ 20 (integers)
Output
H bar rows, the score row, then the number of invalid answers
Example 1 · stdin
12 5
4 5 3 4 0 4 2 5 7 4 1 5
stdout
...#.
...##
...##
#####
12345
2
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

You build a list filled with 0, one slot per score, and count into it.
Slot 0 is score 1, so add to counts[r - 1].
Filling: Python [0] * k, JS/TS new Array(k).fill(0), Java/C# new int[k] (zero by default), C++ std::vector<int> counts(k, 0), C int counts[9] = {0}; (without an initializer a local array starts with garbage), Craykon NewList(k, 0) (새목록(k, 0)).
Trap one: JS new Array(k) alone has empty slots, so counts[r - 1]++ produces undefined + 1 = NaN with no error.
Trap two: without a range check an answer of 0 becomes counts[-1].
Python counts negative indexes from the end, so it silently adds to the last slot (score k), and C/C++ touch memory outside the array (undefined behavior).
Always ask 1 <= r <= k first (a chained comparison in Python, r >= 1 && r <= k elsewhere).
Trap three: with [0] * k, adding to counts[r] raises IndexError for score k.
Trap four: a bar is filled even when the count equals the row height, so use >=.
The largest value: Python max(counts), JS/TS Math.max(...counts), C# counts.Max(), C++ *std::max_element(...), and Craykon compares one by one with Mathf.Max (수학.큰수).

Pythonmain.py · 16 lines
n, k = map(int, input().split())answers = list(map(int, input().split())) counts = [0] * k   # 0번 칸이 1점invalid = 0for r in answers:    if 1 <= r <= k:        counts[r - 1] += 1    else:        invalid += 1 top = max(counts)for level in range(top, 0, -1):   # 맨 위 줄부터    print("".join("#" if c >= level else "." for c in counts))print("".join(str(j) for j in range(1, k + 1)))print(invalid)
JavaScriptmain.js · 16 lines
const [n, k, ...answers] = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number); const counts = new Array(k).fill(0); // 0번 칸이 1점let invalid = 0;for (const r of answers) {  if (r >= 1 && r <= k) counts[r - 1]++;  else invalid++;} const out = [];for (let level = Math.max(...counts); level >= 1; level--) {  out.push(counts.map((c) => (c >= level ? "#" : ".")).join("")); // 맨 위 줄부터}out.push(counts.map((_, j) => j + 1).join(""));out.push(invalid);console.log(out.join("\n"));
TypeScriptmain.ts · 17 lines
import { readFileSync } from "node:fs";const [n, k, ...answers]: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number); const counts: number[] = new Array<number>(k).fill(0); // 0번 칸이 1점let invalid = 0;for (const r of answers) {  if (r >= 1 && r <= k) counts[r - 1]++;  else invalid++;} const out: string[] = [];for (let level = Math.max(...counts); level >= 1; level--) {  out.push(counts.map((c) => (c >= level ? "#" : ".")).join("")); // 맨 위 줄부터}out.push(counts.map((_, j) => j + 1).join(""));out.push(String(invalid));console.log(out.join("\n"));
JavaMain.java · 26 lines
import java.util.Scanner; public class Main {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        int n = sc.nextInt(), k = sc.nextInt();        int[] counts = new int[k]; // Java의 int 배열은 0으로 채워져 있다. 0번 칸이 1점        int invalid = 0;        for (int i = 0; i < n; i++) {            int r = sc.nextInt();            if (r >= 1 && r <= k) counts[r - 1]++;            else invalid++;        }        int top = 0;        for (int c : counts) top = Math.max(top, c);         StringBuilder out = new StringBuilder();        for (int level = top; level >= 1; level--) { // 맨 위 줄부터            for (int c : counts) out.append(c >= level ? '#' : '.');            out.append('\n');        }        for (int j = 1; j <= k; j++) out.append(j);        out.append('\n').append(invalid).append('\n');        System.out.print(out);    }}
C#Main.cs · 30 lines
using System;using System.Linq;using System.Text; class Program{    static void Main()    {        int k = int.Parse(Console.ReadLine().Trim().Split(' ')[1]);        int[] answers = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();         int[] counts = new int[k]; // C#의 int 배열은 0으로 채워져 있다. 0번 칸이 1점        int invalid = 0;        foreach (int r in answers)        {            if (r >= 1 && r <= k) counts[r - 1]++;            else invalid++;        }         var sb = new StringBuilder();        for (int level = counts.Max(); level >= 1; level--) // 맨 위 줄부터        {            foreach (int c in counts) sb.Append(c >= level ? '#' : '.');            sb.Append('\n');        }        for (int j = 1; j <= k; j++) sb.Append(j);        sb.Append('\n').Append(invalid).Append('\n');        Console.Write(sb);    }}
C++main.cpp · 26 lines
#include <algorithm>#include <iostream>#include <string>#include <vector> int main() {    int n, k;    std::cin >> n >> k;    std::vector<int> counts(k, 0); // 0번 칸이 1점    int invalid = 0;    for (int i = 0; i < n; i++) {        int r;        std::cin >> r;        if (r >= 1 && r <= k) counts[r - 1]++;        else invalid++;    }    int top = *std::max_element(counts.begin(), counts.end());     std::string out;    for (int level = top; level >= 1; level--) { // 맨 위 줄부터        for (int c : counts) out += c >= level ? '#' : '.';        out += '\n';    }    for (int j = 1; j <= k; j++) out += std::to_string(j);    std::cout << out << "\n" << invalid << "\n";}
Cmain.c · 25 lines
#include <stdio.h> int main(void) {    int n, k;    scanf("%d %d", &n, &k);    int counts[9] = {0}; /* = {0}이 없으면 지역 배열은 쓰레기 값으로 시작한다. 0번 칸이 1점 */    int invalid = 0;    for (int i = 0; i < n; i++) {        int r;        scanf("%d", &r);        if (r >= 1 && r <= k) counts[r - 1]++;        else invalid++;    }    int top = 0;    for (int j = 0; j < k; j++)        if (counts[j] > top) top = counts[j];     for (int level = top; level >= 1; level--) { /* 맨 위 줄부터 */        for (int j = 0; j < k; j++) putchar(counts[j] >= level ? '#' : '.');        putchar('\n');    }    for (int j = 1; j <= k; j++) printf("%d", j);    printf("\n%d\n", invalid);    return 0;}
Craykonmain.cray · 40 lines
first = Console.ReadNumbers();k = first[1];answers = Console.ReadNumbers(); counts = NewList(k, 0); // 0번 칸이 1점invalid = 0;foreach (r in answers){    if (r >= 1 && r <= k)    {        counts[r - 1] = counts[r - 1] + 1;    }    else    {        invalid++;    }} top = 0;foreach (c in counts){    top = Mathf.Max(top, c);} for (level = top; level >= 1; level--){    row = "";    foreach (c in counts)    {        row = row + (c >= level ? "#" : ".");    }    Console.WriteLine(row);}labels = "";for (j = 1; j <= k; j++){    labels = labels + j;}Console.WriteLine(labels);Console.WriteLine(invalid);