{ }codelper
constantsdeclaring variablesjoined outputP0163

Building a shuttle bus timetable

Build one day's timetable for a company shuttle bus. The route rules are as follows; keep them as constants in your program. - The first bus leaves at 06:00. - Buses may leave up to and including 22:30 (a bus leaving at 22:30 counts).
No bus leaves later than 22:30. - Rush hours are from 07:00 (inclusive) to 09:00 (exclusive) and from 17:00 (inclusive) to 19:00 (exclusive). If a bus leaves during rush hours, the next bus leaves R minutes later; otherwise N minutes later. The input gives N and R. For every hour that has at least one departure, from the earliest hour, print one line with "HH:" followed by that hour's minutes in order, each preceded by a single space (for example "07: 20 35 50"). Write hours and minutes with two digits (6 o'clock is 06, 5 minutes is 05). Hours with no departure get no line. On the last line print "total" and the number of departures in the day, separated by one space.

Input
One line with N and R (1 ≤ R ≤ N ≤ 180, integers)
Output
One line "HH: MM MM …" per hour with departures, then "total count"
Example 1 · stdin
90 30
stdout
06: 00
07: 30
08: 00 30
09: 00
10: 30
12: 00
13: 30
15: 00
16: 30
18: 00 30
19: 00
20: 30
22: 00
total 15
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

Constants are spelled differently in each language.
Python has no syntax for them, so an uppercase name like FIRST = 360 is only a promise.
JS/TS use const, Java static final int, C# const int (arrays and tuples cannot be const, so use static readonly), C #define FIRST (6 * 60) or const int, and C++ constexpr int.
Craykon has no constants, so you keep a variable you promise not to change, first = 6 * 60;.
JS const and Java final only fix the name, so changing an array slot with RUSH[0][0] = 0 is not stopped (TS readonly or JS Object.freeze stops it).
Where you declare variables matters too.
The hour being collected and its list of minutes must be created outside the loop, so that the last hour (22) can still be printed after the loop ends.
In JS/TS (let/const), Java, C#, C and C++ a variable created inside a {} block is not visible outside it, and in Craykon a variable first assigned inside a block is not visible outside either.
Python blocks do not create a scope, so a variable created inside is visible outside.
If you do not start a new minute list when the hour changes, the earlier minutes keep piling up, and if you do not print the last hour after the loop, the 22 line goes missing.
Joining: Python " ".join(minutes), JS/TS minutes.join(" "), Java String.join(" ", minutes), C# string.Join(" ", minutes), Craykon minutes.Join(" ").
C has no join, so print "06:" and then put a space in front of each minute, as in " 00".
If the header is already "06: " you get two spaces.
The boundaries are traps as well: rush hours exclude their end (start <= t && t < end), so the bus after one leaving at 09:00 comes N minutes later, while a bus leaving at 22:30 is included (t <= LAST).
Write hours and minutes with two digits using %02d, padStart(2, "0"), D2, or Craykon PadLeft(2, "0").

Pythonmain.py · 26 lines
# 파이썬에는 상수 문법이 없다: 대문자 이름으로 "바꾸지 않음"을 약속한다FIRST = 6 * 60          # 06:00LAST = 22 * 60 + 30     # 22:30 (이 시각까지 출발할 수 있다)RUSH = ((7 * 60, 9 * 60), (17 * 60, 19 * 60))  # [시작, 끝) — 끝 시각은 들어가지 않는다  def is_rush(t):    return any(start <= t < end for start, end in RUSH)  normal, rush = map(int, input().split())hour = -1      # 지금 모으는 시(반복문 밖에서 만든다)minutes = []   # 그 시의 분들total = 0t = FIRSTwhile t <= LAST:    if t // 60 != hour:        if minutes:            print(f"{hour:02d}: " + " ".join(minutes))        hour = t // 60        minutes = []    minutes.append(f"{t % 60:02d}")    total += 1    t += rush if is_rush(t) else normalprint(f"{hour:02d}: " + " ".join(minutes))  # 마지막 시도 잊지 않는다print("total", total)
JavaScriptmain.js · 25 lines
// const는 다시 넣을 수 없는 이름이다(배열 안의 칸은 바꿀 수 있다)const FIRST = 6 * 60;const LAST = 22 * 60 + 30;const RUSH = [[7 * 60, 9 * 60], [17 * 60, 19 * 60]]; // [시작, 끝) const isRush = (t) => RUSH.some(([start, end]) => start <= t && t < end);const two = (x) => String(x).padStart(2, "0"); const [normal, rush] = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);const out = [];let hour = -1; // 반복문 밖에서 let으로 만들어야 반복이 끝난 뒤에도 쓴다let minutes = [];let total = 0;for (let t = FIRST; t <= LAST; t += isRush(t) ? rush : normal) {  if (Math.floor(t / 60) !== hour) {    if (minutes.length > 0) out.push(`${two(hour)}: ${minutes.join(" ")}`);    hour = Math.floor(t / 60);    minutes = [];  }  minutes.push(two(t % 60));  total++;}out.push(`${two(hour)}: ${minutes.join(" ")}`);out.push(`total ${total}`);console.log(out.join("\n"));
TypeScriptmain.ts · 30 lines
import { readFileSync } from "node:fs";const FIRST = 6 * 60;const LAST = 22 * 60 + 30;// readonly 튜플: 타입 검사기가 칸을 바꾸지 못하게 막는다const RUSH: readonly (readonly [number, number])[] = [[7 * 60, 9 * 60], [17 * 60, 19 * 60]]; // [시작, 끝) function isRush(t: number): boolean {  return RUSH.some(([start, end]) => start <= t && t < end);}function two(x: number): string {  return String(x).padStart(2, "0");} const [normal, rush]: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);const out: string[] = [];let hour: number = -1;let minutes: string[] = [];let total = 0;for (let t = FIRST; t <= LAST; t += isRush(t) ? rush : normal) {  if (Math.floor(t / 60) !== hour) {    if (minutes.length > 0) out.push(`${two(hour)}: ${minutes.join(" ")}`);    hour = Math.floor(t / 60);    minutes = [];  }  minutes.push(two(t % 60));  total++;}out.push(`${two(hour)}: ${minutes.join(" ")}`);out.push(`total ${total}`);console.log(out.join("\n"));
JavaMain.java · 37 lines
import java.util.ArrayList;import java.util.List;import java.util.Scanner; public class Main {    // static final: 한 번 넣으면 바꿀 수 없다(배열이면 이름만 고정이고 칸은 바뀐다)    static final int FIRST = 6 * 60;    static final int LAST = 22 * 60 + 30;    static final int[][] RUSH = {{7 * 60, 9 * 60}, {17 * 60, 19 * 60}}; // [시작, 끝)     static boolean isRush(int t) {        for (int[] w : RUSH)            if (w[0] <= t && t < w[1]) return true;        return false;    }     public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        int normal = sc.nextInt(), rush = sc.nextInt();        StringBuilder out = new StringBuilder();        int hour = -1; // 반복문 밖에서 만든다        List<String> minutes = new ArrayList<>();        int total = 0;        for (int t = FIRST; t <= LAST; t += isRush(t) ? rush : normal) {            if (t / 60 != hour) {                if (!minutes.isEmpty()) out.append(String.format("%02d: ", hour)).append(String.join(" ", minutes)).append('\n');                hour = t / 60;                minutes = new ArrayList<>();            }            minutes.add(String.format("%02d", t % 60));            total++;        }        out.append(String.format("%02d: ", hour)).append(String.join(" ", minutes)).append('\n');        out.append("total ").append(total).append('\n');        System.out.print(out);    }}
C#Main.cs · 42 lines
using System;using System.Collections.Generic;using System.Text; class Program{    // const는 컴파일할 때 정해지는 값만 된다. 배열은 static readonly로    const int First = 6 * 60;    const int Last = 22 * 60 + 30;    static readonly (int Start, int End)[] Rush = { (7 * 60, 9 * 60), (17 * 60, 19 * 60) }; // [시작, 끝)     static bool IsRush(int t)    {        foreach (var w in Rush)            if (w.Start <= t && t < w.End) return true;        return false;    }     static void Main()    {        string[] p = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries);        int normal = int.Parse(p[0]), rush = int.Parse(p[1]);        var sb = new StringBuilder();        int hour = -1; // 반복문 밖에서 만든다        var minutes = new List<string>();        int total = 0;        for (int t = First; t <= Last; t += IsRush(t) ? rush : normal)        {            if (t / 60 != hour)            {                if (minutes.Count > 0) sb.Append($"{hour:D2}: ").Append(string.Join(" ", minutes)).Append('\n');                hour = t / 60;                minutes = new List<string>();            }            minutes.Add($"{t % 60:D2}");            total++;        }        sb.Append($"{hour:D2}: ").Append(string.Join(" ", minutes)).Append('\n');        sb.Append("total ").Append(total).Append('\n');        Console.Write(sb);    }}
C++main.cpp · 42 lines
#include <array>#include <cstdio>#include <iostream>#include <string>#include <utility> // constexpr: 컴파일할 때 값이 정해지는 상수constexpr int FIRST = 6 * 60;constexpr int LAST = 22 * 60 + 30;constexpr std::array<std::pair<int, int>, 2> RUSH{{{7 * 60, 9 * 60}, {17 * 60, 19 * 60}}}; // [시작, 끝) bool isRush(int t) {    for (const auto& [start, end] : RUSH)        if (start <= t && t < end) return true;    return false;} std::string two(int x) {    char buf[4];    std::snprintf(buf, sizeof buf, "%02d", x);    return buf;} int main() {    int normal, rush;    std::cin >> normal >> rush;    std::string out, line;    int hour = -1; // 반복문 밖에서 만든다    int total = 0;    for (int t = FIRST; t <= LAST; t += isRush(t) ? rush : normal) {        if (t / 60 != hour) {            if (!line.empty()) out += line + '\n';            hour = t / 60;            line = two(hour) + ":";        }        line += " " + two(t % 60);        total++;    }    out += line + '\n';    out += "total " + std::to_string(total) + '\n';    std::cout << out;}
Cmain.c · 30 lines
#include <stdio.h> /* #define은 컴파일 전에 글자 그대로 바꿔 넣는다(타입이 없다) */#define FIRST (6 * 60)#define LAST (22 * 60 + 30)static const int RUSH[2][2] = {{7 * 60, 9 * 60}, {17 * 60, 19 * 60}}; /* [시작, 끝) */ static int is_rush(int t) {    for (int i = 0; i < 2; i++)        if (RUSH[i][0] <= t && t < RUSH[i][1]) return 1;    return 0;} int main(void) {    int normal, rush;    scanf("%d %d", &normal, &rush);    int hour = -1; /* 반복문 밖에서 만든다 */    int total = 0;    for (int t = FIRST; t <= LAST; t += is_rush(t) ? rush : normal) {        if (t / 60 != hour) {            if (hour != -1) putchar('\n');            hour = t / 60;            printf("%02d:", hour); /* 사이 빈칸은 분마다 앞에 붙인다 */        }        printf(" %02d", t % 60);        total++;    }    printf("\ntotal %d\n", total);    return 0;}
Craykonmain.cray · 55 lines
// 크레이콘에는 상수가 없다: 바꾸지 않기로 약속한 변수로 둔다첫차 = 6 * 60;막차 = 22 * 60 + 30;붐빔시작 = [7 * 60, 17 * 60];붐빔끝 = [9 * 60, 19 * 60]; 붐비나(t){    for (i = 0; i < 2; i++)    {        if (붐빔시작[i] <= t && t < 붐빔끝[i])        {            return true;        }    }    return false;} 두자리(x){    return ("" + x).PadLeft(2, "0");} 간격들 = Console.ReadNumbers();보통 = 간격들[0];붐빌때 = 간격들[1];// 블록 안에서 처음 넣은 변수는 블록 밖에서 안 보인다: 반복 전에 만든다시 = -1;분들 = [];모두 = 0;t = 첫차;while (t <= 막차){    if (Mathf.Quot(t, 60) != 시)    {        if (분들.Count > 0)        {            Console.WriteLine(두자리(시) + ": " + 분들.Join(" "));        }        시 = Mathf.Quot(t, 60);        분들 = [];    }    분들.Add(두자리(t % 60));    모두 += 1;    if (붐비나(t))    {        t += 붐빌때;    }    else    {        t += 보통;    }}Console.WriteLine(두자리(시) + ": " + 분들.Join(" "));Console.WriteLine("total " + 모두);