{ }codelper
stepping loopsbuilding stringsstring lengthP0172

A ruler made of characters

Draw a ruler with characters. The first line gives the ruler length n and the major tick spacing k, separated by one space. The ruler has n + 1 cells from 0 to n, numbered 0, 1, 2, …, n from the left. The first output line is the tick line.
It has exactly n + 1 characters, and the character at cell c is | if c is a multiple of k, otherwise .
(a period). The second line is the number line.
Look at the multiples of k that are at most n, m = 0, k, 2k, 3k, …, in increasing order, and try to write m in decimal starting at cell m and going right. If m is written, its last cell is m + (number of digits of m) − 1.
If this cell is greater than n, m is not written. Also, if some number has already been written, there must be at least one blank cell between that number's last cell and cell m.
Otherwise m is not written. A number that was skipped has no effect on later decisions. Cells without a number are spaces, and trailing spaces of the number line are not printed. On the third line print how many numbers were written on the number line.

Input
1 ≤ k ≤ n ≤ 5000
Output
Three lines
Example 1 · stdin
25 5
stdout
|....|....|....|....|....|
0    5    10   15   20
5
Example 2 · stdin
12 1
stdout
|||||||||||||
0 2 4 6 8 10
6
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 ticks are a loop that steps by k.
Python range(0, n + 1, k) excludes its end, so you must pass n + 1 to include cell n.
Other languages use for (m = 0; m <= n; m += k), and Craykon for (m = 0; m <= n; m += k) (반복).
Looping the tick line with c < n gives only n characters and drops the last | in the first example.
If you append numbers from left to right, the current length is the next free cell, so 'at least one blank' is m > current length and you add m - current length spaces.
Remembering a skipped number's last cell as 'the previous number' also drops 2, 4 and 6 in the second example.
The fit test is <=; writing < loses the 9 for n = 9, k = 9.
Count digits by turning the number into a string: Python len(str(m)), JS/TS String(m).length, Java Integer.toString(m).length(), C# m.ToString().Length, C++ std::to_string(m).size(), Craykon ("" + m).Length (길이).
In C use the character count that sprintf returns.
Building strings differs too.
In Java and C#, += in a loop copies a new string every time, so use StringBuilder (C# Append(' ', count) adds the spaces at once).
Python, JS/TS, C++ std::string and Craykon are fine with +=; in C fill a char array and put '\0' at the end.
C++ size() is unsigned, so convert it to int before comparing it with m.

Pythonmain.py · 19 lines
n, k = map(int, input().split()) # 눈금 줄: 칸 0 ~ n, 모두 n + 1글자marks = "".join("|" if c % k == 0 else "." for c in range(n + 1)) # 숫자 줄: 0, k, 2k, ... 를 차례로 보며 쓸 수 있는 것만 뒤에 붙인다labels = ""count = 0for m in range(0, n + 1, k):    t = str(m)    fits = m + len(t) - 1 <= n             # 마지막 칸이 n을 넘지 않는다    gap = labels == "" or m > len(labels)  # 앞 숫자와 빈칸이 하나 이상 있다    if fits and gap:        labels += " " * (m - len(labels)) + t        count += 1 print(marks)print(labels)print(count)
JavaScriptmain.js · 19 lines
const [n, k] = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number); // 눈금 줄: 칸 0 ~ n, 모두 n + 1글자let marks = "";for (let c = 0; c <= n; c++) marks += c % k === 0 ? "|" : "."; // 숫자 줄: 0, k, 2k, ... 를 차례로 보며 쓸 수 있는 것만 뒤에 붙인다let labels = "";let count = 0;for (let m = 0; m <= n; m += k) {  const t = String(m);  const fits = m + t.length - 1 <= n; // 마지막 칸이 n을 넘지 않는다  const gap = labels === "" || m > labels.length; // 앞 숫자와 빈칸이 하나 이상 있다  if (fits && gap) {    labels += " ".repeat(m - labels.length) + t;    count++;  }}console.log([marks, labels, count].join("\n"));
TypeScriptmain.ts · 20 lines
import { readFileSync } from "node:fs";const [n, k]: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number); // 눈금 줄: 칸 0 ~ n, 모두 n + 1글자let marks = "";for (let c = 0; c <= n; c++) marks += c % k === 0 ? "|" : "."; // 숫자 줄: 0, k, 2k, ... 를 차례로 보며 쓸 수 있는 것만 뒤에 붙인다let labels = "";let count = 0;for (let m = 0; m <= n; m += k) {  const t: string = String(m);  const fits: boolean = m + t.length - 1 <= n; // 마지막 칸이 n을 넘지 않는다  const gap: boolean = labels === "" || m > labels.length; // 앞 숫자와 빈칸이 하나 이상 있다  if (fits && gap) {    labels += " ".repeat(m - labels.length) + t;    count++;  }}console.log([marks, labels, String(count)].join("\n"));
JavaMain.java · 28 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();         // 눈금 줄: 칸 0 ~ n, 모두 n + 1글자        StringBuilder marks = new StringBuilder();        for (int c = 0; c <= n; c++) marks.append(c % k == 0 ? '|' : '.');         // 숫자 줄: 0, k, 2k, ... 를 차례로 보며 쓸 수 있는 것만 뒤에 붙인다        StringBuilder labels = new StringBuilder();        int count = 0;        for (int m = 0; m <= n; m += k) {            String t = Integer.toString(m);            boolean fits = m + t.length() - 1 <= n; // 마지막 칸이 n을 넘지 않는다            boolean gap = labels.length() == 0 || m > labels.length(); // 앞 숫자와 빈칸이 하나 이상            if (fits && gap) {                labels.append(" ".repeat(m - labels.length())).append(t);                count++;            }        }        System.out.println(marks);        System.out.println(labels);        System.out.println(count);    }}
C#Main.cs · 33 lines
using System;using System.Text; class Program{    static void Main()    {        string[] p = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries);        int n = int.Parse(p[0]), k = int.Parse(p[1]);         // 눈금 줄: 칸 0 ~ n, 모두 n + 1글자        var marks = new StringBuilder();        for (int c = 0; c <= n; c++) marks.Append(c % k == 0 ? '|' : '.');         // 숫자 줄: 0, k, 2k, ... 를 차례로 보며 쓸 수 있는 것만 뒤에 붙인다        var labels = new StringBuilder();        int count = 0;        for (int m = 0; m <= n; m += k)        {            string t = m.ToString();            bool fits = m + t.Length - 1 <= n; // 마지막 칸이 n을 넘지 않는다            bool gap = labels.Length == 0 || m > labels.Length; // 앞 숫자와 빈칸이 하나 이상            if (fits && gap)            {                labels.Append(' ', m - labels.Length).Append(t);                count++;            }        }        Console.WriteLine(marks);        Console.WriteLine(labels);        Console.WriteLine(count);    }}
C++main.cpp · 26 lines
#include <iostream>#include <string> int main() {    int n, k;    std::cin >> n >> k;     // 눈금 줄: 칸 0 ~ n, 모두 n + 1글자    std::string marks;    for (int c = 0; c <= n; c++) marks += c % k == 0 ? '|' : '.';     // 숫자 줄: 0, k, 2k, ... 를 차례로 보며 쓸 수 있는 것만 뒤에 붙인다    std::string labels;    int count = 0;    for (int m = 0; m <= n; m += k) {        std::string t = std::to_string(m);        int len = static_cast<int>(labels.size()); // size()는 부호 없는 수라 int로 바꿔 비교한다        bool fits = m + static_cast<int>(t.size()) - 1 <= n; // 마지막 칸이 n을 넘지 않는다        bool gap = len == 0 || m > len;                      // 앞 숫자와 빈칸이 하나 이상 있다        if (fits && gap) {            labels += std::string(m - len, ' ') + t;            count++;        }    }    std::cout << marks << '\n' << labels << '\n' << count << '\n';}
Cmain.c · 33 lines
#include <stdio.h>#include <string.h> #define MAXN 5000 int main(void) {    int n, k;    scanf("%d %d", &n, &k);     /* 눈금 줄: 칸 0 ~ n, 모두 n + 1글자 */    static char marks[MAXN + 2];    for (int c = 0; c <= n; c++) marks[c] = c % k == 0 ? '|' : '.';    marks[n + 1] = '\0';     /* 숫자 줄: 0, k, 2k, ... 를 차례로 보며 쓸 수 있는 것만 뒤에 붙인다 */    static char labels[MAXN + 2];    int len = 0, count = 0;    char t[8];    for (int m = 0; m <= n; m += k) {        int w = sprintf(t, "%d", m);          /* sprintf는 쓴 글자 수를 돌려준다 */        int fits = m + w - 1 <= n;            /* 마지막 칸이 n을 넘지 않는다 */        int gap = len == 0 || m > len;        /* 앞 숫자와 빈칸이 하나 이상 있다 */        if (fits && gap) {            while (len < m) labels[len++] = ' ';            memcpy(labels + len, t, w);            len += w;            count++;        }    }    labels[len] = '\0';    printf("%s\n%s\n%d\n", marks, labels, count);    return 0;}
Craykonmain.cray · 35 lines
v = Console.ReadNumbers();n = v[0];k = v[1]; // 눈금 줄: 칸 0 ~ n, 모두 n + 1글자눈금 = "";for (c = 0; c <= n; c += 1){    if (c % k == 0)    {        눈금 += "|";    }    else    {        눈금 += ".";    }} // 숫자 줄: 0, k, 2k, ... 를 차례로 보며 쓸 수 있는 것만 뒤에 붙인다숫자줄 = "";개수 = 0;for (m = 0; m <= n; m += k){    t = "" + m;    맞음 = m + t.Length - 1 <= n; // 마지막 칸이 n을 넘지 않는다    띄움 = 숫자줄 == "" || m > 숫자줄.Length; // 앞 숫자와 빈칸이 하나 이상 있다    if (맞음 && 띄움)    {        숫자줄 += " ".Repeat(m - 숫자줄.Length) + t;        개수 += 1;    }}Console.WriteLine(눈금);Console.WriteLine(숫자줄);Console.WriteLine(개수);