{ }codelper
printing without newlinetype conversionP0164

Temperature strip chart

A weather station measured the temperature h times a day for d days. Each temperature is recorded as an integer in tenths of a degree (-35 means -3.5 degrees). The first line gives d and h, and each of the next d lines gives that day's h temperatures, separated by spaces. Let lo be the lowest and hi the highest of all the records. The cell number of a temperature x is (x − lo) × 9 ÷ (hi − lo + 1) with the fractional part dropped; it is between 0 and 8. Cell numbers 0–8 are drawn with the characters . : - = + * # % @ in that order. For each day print one line with its h cell characters in the order measured, with no spaces between them. On the last line print lo and hi in degrees with one decimal place, separated by one space (-35 is -3.5, 0 is 0.0, 200 is 20.0). Since every temperature is in tenths, these two values are exact to one decimal place.

Input
1 ≤ d ≤ 100, 1 ≤ h ≤ 48, -400 ≤ temperature ≤ 500 (integers)
Output
d lines of cell characters (h per line), then "lo hi" in degrees with one decimal
Example 1 · stdin
2 5
-35 -10 42 118 97
12 60 155 203 140
stdout
..-*+
:=%@#
-3.5 20.3
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

The number changes type in two places.
(1) Cell number: in C, C++, Java and C#, / between ints keeps only the quotient, so multiply first.
Writing (x - lo) / width * 9 gives 0 every time because x - lo is always smaller than width, so every cell is ..
In Python 3, JS, TS and Craykon / gives a real number, so turn it into an integer before using it as an index: Python // (plain / raises TypeError at SCALE[2.0]), JS/TS Math.floor (otherwise SCALE[2.5] is undefined), Craykon Mathf.Floor.
The divisor is hi - lo + 1.
Without + 1 the highest value lands in a cell 9 that does not exist, and when all values are equal you divide by zero.
The cells use the overall lo and hi, not each day's.
(2) Writing tenths as degrees: converting to floating point and dividing (lo / 10.0, or lo / 10 in Python and JS) is safe.
Building "integer.digit" from a quotient and a remainder breaks on negatives: in C, C++, Java and C# -5 / 10 is 0 (and JS Math.trunc(-5 / 10) also prints as 0), so -0.5 becomes 0.5, and in Python -5 // 10 is -1 and -5 % 10 is 5, giving -1.5.
One decimal place: Python f"{x:.1f}", JS/TS toFixed(1), C printf("%.1f"), C++ std::fixed << std::setprecision(1), Java String.format(Locale.ROOT, "%.1f", x), C# ToString("F1", CultureInfo.InvariantCulture), Craykon Str.Fixed(x, 1).
Writing one character at a time without a newline: Python print(c, end=""), JS/TS process.stdout.write(c) (console.log always ends the line), Java System.out.print (slow when called many times, so collect in a PrintWriter), C# Console.Write (here collected in a StreamWriter), C putchar, C++ std::cout << c, Craykon Console.Write.
End each line with its own newline.
In C, do not collect a line and print it with printf(row): the character % is read as a format, so %% becomes a single %.
Use fputs(row, stdout) or printf("%s", row).

Pythonmain.py · 14 lines
SCALE = ".:-=+*#%@"  # 낮은 칸부터 높은 칸까지 아홉 글자 d, h = map(int, input().split())days = [list(map(int, input().split())) for _ in range(d)]lo = min(min(day) for day in days)hi = max(max(day) for day in days)width = hi - lo + 1for day in days:    for x in day:        # // 로 나눠야 정수다. / 는 실수라서 SCALE[2.5]처럼 칸 번호로 쓸 수 없다        print(SCALE[(x - lo) * 9 // width], end="")    print()# 0.1도 단위 정수를 실수로 바꿔 10으로 나눈다: -5 → -0.5print(f"{lo / 10:.1f} {hi / 10:.1f}")
JavaScriptmain.js · 16 lines
const SCALE = ".:-=+*#%@"; // 낮은 칸부터 높은 칸까지 아홉 글자const nums = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);const [d, h] = nums;const temps = nums.slice(2);const lo = Math.min(...temps);const hi = Math.max(...temps);const width = hi - lo + 1;for (let i = 0; i < d; i++) {  for (let j = 0; j < h; j++) {    const x = temps[i * h + j];    // / 는 실수라서 Math.floor로 정수 칸 번호를 만든다(SCALE[2.5]는 undefined)    process.stdout.write(SCALE[Math.floor(((x - lo) * 9) / width)]); // 줄을 바꾸지 않고 쓴다  }  process.stdout.write("\n");}console.log(`${(lo / 10).toFixed(1)} ${(hi / 10).toFixed(1)}`);
TypeScriptmain.ts · 17 lines
import { readFileSync } from "node:fs";const SCALE = ".:-=+*#%@"; // 낮은 칸부터 높은 칸까지 아홉 글자const nums: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);const [d, h] = nums;const temps: number[] = nums.slice(2);const lo: number = Math.min(...temps);const hi: number = Math.max(...temps);const width: number = hi - lo + 1;for (let i = 0; i < d; i++) {  for (let j = 0; j < h; j++) {    const x: number = temps[i * h + j];    // / 는 실수라서 Math.floor로 정수 칸 번호를 만든다    process.stdout.write(SCALE[Math.floor(((x - lo) * 9) / width)]); // 줄을 바꾸지 않고 쓴다  }  process.stdout.write("\n");}console.log(`${(lo / 10).toFixed(1)} ${(hi / 10).toFixed(1)}`);
JavaMain.java · 36 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.util.Locale;import java.util.StringTokenizer; public class Main {    static final String SCALE = ".:-=+*#%@"; // 낮은 칸부터 높은 칸까지 아홉 글자     public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        StringTokenizer st = new StringTokenizer(in.readLine());        int d = Integer.parseInt(st.nextToken()), h = Integer.parseInt(st.nextToken());        int[][] t = new int[d][h];        int lo = Integer.MAX_VALUE, hi = Integer.MIN_VALUE;        for (int i = 0; i < d; i++) {            st = new StringTokenizer(in.readLine());            for (int j = 0; j < h; j++) {                t[i][j] = Integer.parseInt(st.nextToken());                lo = Math.min(lo, t[i][j]);                hi = Math.max(hi, t[i][j]);            }        }        int width = hi - lo + 1;        PrintWriter out = new PrintWriter(System.out); // print를 여러 번 해도 한 번에 내보낸다        for (int[] day : t) {            // int끼리는 몫만 남는다: 곱하기를 먼저 해야 한다((x - lo) / width * 9는 늘 0)            for (int x : day) out.print(SCALE.charAt((x - lo) * 9 / width));            out.println();        }        // int를 double로 바꿔 나눈다: -5 / 10은 0이지만 -5 / 10.0은 -0.5        out.println(String.format(Locale.ROOT, "%.1f %.1f", lo / 10.0, hi / 10.0));        out.flush();    }}
C#Main.cs · 31 lines
using System;using System.Globalization;using System.IO;using System.Linq; class Program{    const string Scale = ".:-=+*#%@"; // 낮은 칸부터 높은 칸까지 아홉 글자     static void Main()    {        int[] dh = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();        int d = dh[0];        var days = new int[d][];        for (int i = 0; i < d; i++)            days[i] = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();        int lo = days.Min(r => r.Min()), hi = days.Max(r => r.Max());        int width = hi - lo + 1;        var out_ = new StreamWriter(Console.OpenStandardOutput()); // Write를 여러 번 해도 한 번에 내보낸다        foreach (int[] day in days)        {            // int끼리는 몫만 남는다: 곱하기를 먼저            foreach (int x in day) out_.Write(Scale[(x - lo) * 9 / width]);            out_.Write('\n');        }        // int를 double로 바꿔 나눈다: -5 / 10은 0, -5 / 10.0은 -0.5        var inv = CultureInfo.InvariantCulture;        out_.Write((lo / 10.0).ToString("F1", inv) + " " + (hi / 10.0).ToString("F1", inv) + "\n");        out_.Flush();    }}
C++main.cpp · 28 lines
#include <algorithm>#include <iomanip>#include <iostream>#include <string>#include <vector> int main() {    const std::string SCALE = ".:-=+*#%@"; // 낮은 칸부터 높은 칸까지 아홉 글자    std::ios::sync_with_stdio(false);    int d, h;    std::cin >> d >> h;    std::vector<std::vector<int>> t(d, std::vector<int>(h));    int lo = 1000, hi = -1000;    for (auto& day : t)        for (int& x : day) {            std::cin >> x;            lo = std::min(lo, x);            hi = std::max(hi, x);        }    int width = hi - lo + 1;    for (const auto& day : t) {        // int끼리는 몫만 남는다: 곱하기를 먼저. << 는 줄을 바꾸지 않는다        for (int x : day) std::cout << SCALE[(x - lo) * 9 / width];        std::cout << '\n';    }    // int를 double로 바꿔 나눈다: -5 / 10은 0이지만 -5 / 10.0은 -0.5    std::cout << std::fixed << std::setprecision(1) << lo / 10.0 << ' ' << hi / 10.0 << '\n';}
Cmain.c · 25 lines
#include <stdio.h> static const char SCALE[] = ".:-=+*#%@"; /* 낮은 칸부터 높은 칸까지 아홉 글자 */static int t[100][48]; int main(void) {    int d, h;    scanf("%d %d", &d, &h);    int lo = 1000, hi = -1000;    for (int i = 0; i < d; i++)        for (int j = 0; j < h; j++) {            scanf("%d", &t[i][j]);            if (t[i][j] < lo) lo = t[i][j];            if (t[i][j] > hi) hi = t[i][j];        }    int width = hi - lo + 1;    for (int i = 0; i < d; i++) {        /* int끼리는 몫만 남는다: 곱하기를 먼저. putchar는 줄을 바꾸지 않는다 */        for (int j = 0; j < h; j++) putchar(SCALE[(t[i][j] - lo) * 9 / width]);        putchar('\n');    }    /* int를 double로 바꿔 나눈다: -5 / 10은 0이지만 -5 / 10.0은 -0.5 */    printf("%.1f %.1f\n", lo / 10.0, hi / 10.0);    return 0;}
Craykonmain.cray · 30 lines
// 낮은 칸부터 높은 칸까지 아홉 글자눈금 = ".:-=+*#%@";첫줄 = Console.ReadNumbers();d = 첫줄[0];날들 = [];for (i = 0; i < d; i++){    날들.Add(Console.ReadNumbers());}가장낮음 = 날들[0][0];가장높음 = 날들[0][0];foreach (날 in 날들){    foreach (x in 날)    {        가장낮음 = Mathf.Min(가장낮음, x);        가장높음 = Mathf.Max(가장높음, x);    }}폭 = 가장높음 - 가장낮음 + 1;foreach (날 in 날들){    foreach (x in 날)    {        // / 는 소수까지 나눈다: 칸 번호는 수학.내림으로 정수로        Console.Write(눈금[Mathf.Floor((x - 가장낮음) * 9 / 폭)]);    }    Console.WriteLine("");}Console.WriteLine(Str.Fixed(가장낮음 / 10, 1) + " " + Str.Fixed(가장높음 / 10, 1));