{ }codelper
repeating stringsstring lengthoverflowP0175

A horizontal bar report

Print each item's value as a horizontal bar report drawn with characters. The first line gives the number of items n and the longest bar length W, separated by one space. Each of the next n lines gives an item's name and value v, separated by one space. Let M be the largest of all values. An item's bar length is v × W ÷ M with the fractional part dropped.
If M is 0, every bar length is 0. Print one line per item in input order. A line is the name, spaces that pad the name to the length of the longest name, " |", the bar mark, one space, and the value v, joined in this order. The bar mark is # written bar-length times. However, if v is greater than 0 but the bar length is 0, the bar mark is a single .
(period).

Input
1 ≤ n ≤ 500, 1 ≤ W ≤ 100, 0 ≤ v ≤ 10^9 (integers).
Names have length 1 to 20 and use only English letters, digits and _
Output
n lines
Example 1 · stdin
4 20
apple 120
banana 45
kiwi 0
fig 3
stdout
apple  |#################### 120
banana |####### 45
kiwi   | 0
fig    |. 3
Example 2 · stdin
2 5
x 0
y 0
stdout
x | 0
y | 0
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

Multiply before dividing.
Doing integer division first, v / M * W, makes almost every bar 0 except the largest.
But then v * W reaches 1e9 × 100 = 1e11, beyond an int (about 2.1 billion).
Multiply as long long in C/C++ and long in Java/C#.
Python integers have no limit, and JS/TS/Craykon numbers are exact integers up to 2^53, so Math.floor(v * W / M) and Craykon Mathf.Floor(v * w / max) (수학.내림) work.
If M is 0 you would divide by zero, so check it first (second example).
Repeating a character: Python "#" * k, JS/TS/Java "#".repeat(k), C# new string('#', k), C++ std::string(k, '#'), Craykon "#".Repeat(k) (되풀이).
In C call putchar k times.
Padding names goes with measuring length: Python len(s), JS/TS s.length, Java s.length(), C# s.Length, C strlen(s), C++ s.size(), Craykon s.Length (길이); the missing spaces are (longest length − name length).
C printf("%-*s", width, s) takes the width as an argument and left-aligns.
Rounding turns banana in the first example from 7.5 into 8, so always drop the fraction.
Forgetting the .
when v is greater than 0 but the bar is 0 is another common mistake.

Pythonmain.py · 16 lines
import sys data = sys.stdin.read().split()n, w = int(data[0]), int(data[1])names = data[2::2][:n]values = [int(x) for x in data[3::2][:n]] width = max(len(s) for s in names)  # 가장 긴 이름에 맞춘다top = max(values)for name, v in zip(names, values):    bar = v * w // top if top > 0 else 0  # 곱한 뒤에 나눈다(먼저 나누면 0이 된다)    if v > 0 and bar == 0:        mark = "."    else:        mark = "#" * bar    print(name + " " * (width - len(name)) + " |" + mark + " " + str(v))
JavaScriptmain.js · 20 lines
const data = require("fs").readFileSync(0, "utf8").trim().split(/\s+/);const n = Number(data[0]);const w = Number(data[1]);const names = [];const values = [];for (let i = 0; i < n; i++) {  names.push(data[2 + 2 * i]);  values.push(Number(data[3 + 2 * i]));}const width = Math.max(...names.map((s) => s.length)); // 가장 긴 이름에 맞춘다const top = Math.max(...values);const out = [];for (let i = 0; i < n; i++) {  const v = values[i];  // 곱한 뒤에 나눈다. v * w는 1000억까지라 Number로 정확하다  const bar = top > 0 ? Math.floor((v * w) / top) : 0;  const mark = v > 0 && bar === 0 ? "." : "#".repeat(bar);  out.push(names[i] + " ".repeat(width - names[i].length) + " |" + mark + " " + v);}console.log(out.join("\n"));
TypeScriptmain.ts · 21 lines
import { readFileSync } from "node:fs";const data: string[] = readFileSync(0, "utf8").trim().split(/\s+/);const n: number = Number(data[0]);const w: number = Number(data[1]);const names: string[] = [];const values: number[] = [];for (let i = 0; i < n; i++) {  names.push(data[2 + 2 * i]);  values.push(Number(data[3 + 2 * i]));}const width: number = Math.max(...names.map((s) => s.length)); // 가장 긴 이름에 맞춘다const top: number = Math.max(...values);const out: string[] = [];for (let i = 0; i < n; i++) {  const v: number = values[i];  // 곱한 뒤에 나눈다. v * w는 1000억까지라 number로 정확하다  const bar: number = top > 0 ? Math.floor((v * w) / top) : 0;  const mark: string = v > 0 && bar === 0 ? "." : "#".repeat(bar);  out.push(names[i] + " ".repeat(width - names[i].length) + " |" + mark + " " + v);}console.log(out.join("\n"));
JavaMain.java · 33 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.StringTokenizer; public class Main {    public static void main(String[] args) throws IOException {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        StringTokenizer st = new StringTokenizer(br.readLine());        int n = Integer.parseInt(st.nextToken()), w = Integer.parseInt(st.nextToken());        String[] names = new String[n];        long[] values = new long[n];        int width = 0;        long top = 0;        for (int i = 0; i < n; i++) {            st = new StringTokenizer(br.readLine());            names[i] = st.nextToken();            values[i] = Long.parseLong(st.nextToken());            width = Math.max(width, names[i].length()); // 가장 긴 이름에 맞춘다            top = Math.max(top, values[i]);        }        StringBuilder out = new StringBuilder();        for (int i = 0; i < n; i++) {            long v = values[i];            // v * w는 1000억까지 가서 int로는 넘친다. long으로 곱한 뒤에 나눈다            int bar = top > 0 ? (int) (v * w / top) : 0;            String mark = v > 0 && bar == 0 ? "." : "#".repeat(bar);            out.append(names[i]).append(" ".repeat(width - names[i].length()))               .append(" |").append(mark).append(' ').append(v).append('\n');        }        System.out.print(out);    }}
C#Main.cs · 34 lines
using System;using System.Text; class Program{    static void Main()    {        string[] first = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries);        int n = int.Parse(first[0]), w = int.Parse(first[1]);        var names = new string[n];        var values = new long[n];        int width = 0;        long top = 0;        for (int i = 0; i < n; i++)        {            string[] p = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries);            names[i] = p[0];            values[i] = long.Parse(p[1]);            width = Math.Max(width, names[i].Length); // 가장 긴 이름에 맞춘다            top = Math.Max(top, values[i]);        }        var sb = new StringBuilder();        for (int i = 0; i < n; i++)        {            long v = values[i];            // v * w는 1000억까지 가서 int로는 넘친다. long으로 곱한 뒤에 나눈다            int bar = top > 0 ? (int)(v * w / top) : 0;            string mark = v > 0 && bar == 0 ? "." : new string('#', bar);            sb.Append(names[i]).Append(' ', width - names[i].Length)              .Append(" |").Append(mark).Append(' ').Append(v).Append('\n');        }        Console.Write(sb);    }}
C++main.cpp · 25 lines
#include <algorithm>#include <iostream>#include <string>#include <vector> int main() {    int n, w;    std::cin >> n >> w;    std::vector<std::string> names(n);    std::vector<long long> values(n);    std::size_t width = 0;    long long top = 0;    for (int i = 0; i < n; i++) {        std::cin >> names[i] >> values[i];        width = std::max(width, names[i].size()); // 가장 긴 이름에 맞춘다        top = std::max(top, values[i]);    }    for (int i = 0; i < n; i++) {        long long v = values[i];        // v * w는 1000억까지 가서 int로는 넘친다. long long으로 곱한 뒤에 나눈다        int bar = top > 0 ? static_cast<int>(v * w / top) : 0;        std::string mark = v > 0 && bar == 0 ? "." : std::string(bar, '#');        std::cout << names[i] << std::string(width - names[i].size(), ' ') << " |" << mark << ' ' << v << '\n';    }}
Cmain.c · 27 lines
#include <stdio.h>#include <string.h> int main(void) {    int n, w;    static char names[500][24];    static long long values[500];    scanf("%d %d", &n, &w);    int width = 0;    long long top = 0;    for (int i = 0; i < n; i++) {        scanf("%23s %lld", names[i], &values[i]);        int len = (int)strlen(names[i]);        if (len > width) width = len; /* 가장 긴 이름에 맞춘다 */        if (values[i] > top) top = values[i];    }    for (int i = 0; i < n; i++) {        long long v = values[i];        /* v * w는 1000억까지 가서 int로는 넘친다. long long으로 곱한 뒤에 나눈다 */        int bar = top > 0 ? (int)(v * w / top) : 0;        printf("%-*s |", width, names[i]); /* %-*s: 너비를 인자로 받아 왼쪽 맞춤 */        if (v > 0 && bar == 0) putchar('.');        for (int k = 0; k < bar; k++) putchar('#');        printf(" %lld\n", v);    }    return 0;}
Craykonmain.cray · 30 lines
첫줄 = Console.ReadNumbers();n = 첫줄[0];w = 첫줄[1];이름들 = [];값들 = [];너비 = 0;최대 = 0;for (i = 0; i < n; i += 1){    p = Console.ReadLine().Trim().Split();    이름들.Add(p[0]);    값들.Add(p[1].ToNumber());    너비 = Mathf.Max(너비, p[0].Length); // 가장 긴 이름에 맞춘다    최대 = Mathf.Max(최대, p[1].ToNumber());}for (i = 0; i < n; i += 1){    v = 값들[i];    막대 = 0;    if (최대 > 0)    {        막대 = Mathf.Floor(v * w / 최대); // 곱한 뒤에 나눈다    }    표시 = "#".Repeat(막대);    if (v > 0 && 막대 == 0)    {        표시 = ".";    }    Console.WriteLine(이름들[i] + " ".Repeat(너비 - 이름들[i].Length) + " |" + 표시 + " " + v);}