{ }codelper
reading numbersprinting decimalstype conversionP0162

Tidying a bike ride log

A bike computer recorded, for each of n segments, the distance ridden (meters) and the time taken (seconds), as integers. The first line gives n, the second line gives the n segment distances, and the third line gives the n segment times, separated by spaces. For each segment print its speed and its pace on one line, separated by one space. The speed is in kilometers per hour (distance ÷ time × 3.6), rounded to two decimal places and written with exactly two decimals (18 is 18.00). The pace is the number of seconds needed for 1 km (time × 1000 ÷ distance) with the fractional part dropped, giving an integer p, written as "minutes:seconds". The minutes are p divided by 60 (integer quotient), written without leading zeros (3 minutes is 3, 0 minutes is 0), and not converted to hours even when 60 or more. The seconds are the remainder of p divided by 60, always written with two digits (5 seconds is 05). On the last line print "TOTAL", the total speed and the total pace, separated by single spaces. The total speed and pace are not averages of the segment values; compute them as above from the sum of all distances and the sum of all times. To avoid rounding ambiguity, every speed to be printed (including the total) is such that 100 times it has a fractional part of at most 0.4 or at least 0.6.

Input
1 ≤ n ≤ 5000, 1 ≤ distance ≤ 100000, 1 ≤ time ≤ 36000, all integers
Output
n + 1 lines: "speed min:sec" per segment, then "TOTAL speed min:sec"
Example 1 · stdin
3
1000 5000 2500
200 600 487
stdout
18.00 3:20
30.00 2:00
18.48 3:14
TOTAL 23.78 2:31
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 point is when the number changes type.
In C, C++, Java and C#, / between two ints keeps only the quotient, so convert one side to floating point before dividing: (double) m / s * 3.6.
Wrapping it as (double) (m / s) converts after the integer division, so 2500 ÷ 487 in the example's third segment becomes 5, and you print 18.00 instead of 18.48.
In Python 3, JS, TS and Craykon / is always real division, so that trap is absent, but the pace needs its own truncation: Python //, JS/TS Math.floor, Craykon Mathf.Floor (and the minutes with Mathf.Quot(p, 60)).
In Craykon, p % 60 without flooring gives values like 20.5 seconds.
Rounding (round) instead of truncating turns 61.66 seconds into 1:02.
The total pace uses total time × 1000, which for 5000 segments × 36000 seconds is 180 billion, beyond int (about 2.1 billion): accumulate in long long in C/C++ and long in Java/C#.
Numbers in JS, TS and Craykon are exact up to 2^53, so they are fine.
To read many numbers: Python map(int, input().split()), JS/TS read everything and split(/\s+/), Java StringTokenizer, C# Split + int.Parse, C scanf("%d"), C++ cin >>, Craykon Console.ReadNumbers().
Two decimals: Python f"{x:.2f}", JS/TS toFixed(2), C/C++ printf("%.2f"), Java String.format(Locale.ROOT, "%.2f", x), C# ToString("F2", CultureInfo.InvariantCulture), Craykon Str.Fixed(x, 2).
Do not forget to pad the seconds to two digits: %02d, padStart(2, "0"), D2, Craykon PadLeft(2, "0").
And the total speed is not the mean of the segment speeds: in the example the mean is 22.16, but total distance ÷ total time is 23.78.

Pythonmain.py · 17 lines
def pace(seconds, meters):    # 1km에 걸리는 초 = seconds × 1000 ÷ meters, 소수 부분은 버린다(정수 나눗셈 //)    p = seconds * 1000 // meters    return f"{p // 60}:{p % 60:02d}"  def speed(meters, seconds):    return f"{meters / seconds * 3.6:.2f}"  # 파이썬 3의 / 는 늘 실수 나눗셈  n = int(input())ds = list(map(int, input().split()))ts = list(map(int, input().split()))for d, t in zip(ds, ts):    print(speed(d, t), pace(t, d))total_d, total_t = sum(ds), sum(ts)print("TOTAL", speed(total_d, total_t), pace(total_t, total_d))
JavaScriptmain.js · 20 lines
const [n, ...rest] = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);const ds = rest.slice(0, n);const ts = rest.slice(n, 2 * n); const speed = (m, s) => ((m / s) * 3.6).toFixed(2);const pace = (s, m) => {  const p = Math.floor((s * 1000) / m); // JS의 / 는 실수 나눗셈이라 버림을 따로 한다  return `${Math.floor(p / 60)}:${String(p % 60).padStart(2, "0")}`;}; const out = [];let totalD = 0;let totalT = 0;for (let i = 0; i < n; i++) {  out.push(`${speed(ds[i], ts[i])} ${pace(ts[i], ds[i])}`);  totalD += ds[i];  totalT += ts[i];}out.push(`TOTAL ${speed(totalD, totalT)} ${pace(totalT, totalD)}`);console.log(out.join("\n"));
TypeScriptmain.ts · 23 lines
import { readFileSync } from "node:fs";const [n, ...rest]: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);const ds: number[] = rest.slice(0, n);const ts: number[] = rest.slice(n, 2 * n); function speed(m: number, s: number): string {  return ((m / s) * 3.6).toFixed(2);}function pace(s: number, m: number): string {  const p: number = Math.floor((s * 1000) / m); // number 하나뿐이라 버림을 따로 한다  return `${Math.floor(p / 60)}:${String(p % 60).padStart(2, "0")}`;} const out: string[] = [];let totalD = 0;let totalT = 0;for (let i = 0; i < n; i++) {  out.push(`${speed(ds[i], ts[i])} ${pace(ts[i], ds[i])}`);  totalD += ds[i];  totalT += ts[i];}out.push(`TOTAL ${speed(totalD, totalT)} ${pace(totalT, totalD)}`);console.log(out.join("\n"));
JavaMain.java · 41 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.Locale;import java.util.StringTokenizer; public class Main {    static int[] readInts(BufferedReader in, int n) throws IOException {        StringTokenizer st = new StringTokenizer(in.readLine());        int[] a = new int[n];        for (int i = 0; i < n; i++) a[i] = Integer.parseInt(st.nextToken());        return a;    }     // 나누기 전에 double로 바꾼다: (double) (m / s)는 이미 정수로 나눈 뒤라 늦다    static String speed(long m, long s) {        return String.format(Locale.ROOT, "%.2f", (double) m / s * 3.6);    }     // long끼리 나누면 소수 부분이 버려진다. 전체 시간 × 1000은 int를 넘는다    static String pace(long s, long m) {        long p = s * 1000 / m;        return String.format("%d:%02d", p / 60, p % 60);    }     public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        int n = Integer.parseInt(in.readLine().trim());        int[] ds = readInts(in, n);        int[] ts = readInts(in, n);        StringBuilder out = new StringBuilder();        long totalD = 0, totalT = 0;        for (int i = 0; i < n; i++) {            out.append(speed(ds[i], ts[i])).append(' ').append(pace(ts[i], ds[i])).append('\n');            totalD += ds[i];            totalT += ts[i];        }        out.append("TOTAL ").append(speed(totalD, totalT)).append(' ').append(pace(totalT, totalD)).append('\n');        System.out.print(out);    }}
C#Main.cs · 34 lines
using System;using System.Globalization;using System.Linq;using System.Text; class Program{    // 나누기 전에 double로: (double)(m / s)는 정수로 나눈 뒤라 늦다    static string Speed(long m, long s) => ((double)m / s * 3.6).ToString("F2", CultureInfo.InvariantCulture);     // long끼리 나누면 소수 부분이 버려진다. 전체 시간 × 1000은 int를 넘는다    static string Pace(long s, long m)    {        long p = s * 1000 / m;        return $"{p / 60}:{p % 60:D2}";    }     static void Main()    {        int n = int.Parse(Console.ReadLine());        int[] ds = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();        int[] ts = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();        var sb = new StringBuilder();        long totalD = 0, totalT = 0;        for (int i = 0; i < n; i++)        {            sb.Append(Speed(ds[i], ts[i])).Append(' ').Append(Pace(ts[i], ds[i])).Append('\n');            totalD += ds[i];            totalT += ts[i];        }        sb.Append("TOTAL ").Append(Speed(totalD, totalT)).Append(' ').Append(Pace(totalT, totalD)).Append('\n');        Console.Write(sb);    }}
C++main.cpp · 36 lines
#include <cstdio>#include <iostream>#include <vector> // 나누기 전에 double로: static_cast<double>(m / s)는 정수로 나눈 뒤라 늦다void printSpeed(long long m, long long s) {    std::printf("%.2f", static_cast<double>(m) / s * 3.6);} // long long끼리 나누면 소수 부분이 버려진다. 전체 시간 × 1000은 int를 넘는다void printPace(long long s, long long m) {    long long p = s * 1000 / m;    std::printf("%lld:%02lld", p / 60, p % 60);} int main() {    int n;    std::cin >> n;    std::vector<int> ds(n), ts(n);    for (int& d : ds) std::cin >> d;    for (int& t : ts) std::cin >> t;    long long totalD = 0, totalT = 0;    for (int i = 0; i < n; i++) {        printSpeed(ds[i], ts[i]);        std::printf(" ");        printPace(ts[i], ds[i]);        std::printf("\n");        totalD += ds[i];        totalT += ts[i];    }    std::printf("TOTAL ");    printSpeed(totalD, totalT);    std::printf(" ");    printPace(totalT, totalD);    std::printf("\n");}
Cmain.c · 36 lines
#include <stdio.h> static int ds[5000], ts[5000]; /* 나누기 전에 double로: (double)(m / s)는 정수로 나눈 뒤라 늦다 */static void print_speed(long long m, long long s) {    printf("%.2f", (double)m / s * 3.6);} /* long long끼리 나누면 소수 부분이 버려진다. 전체 시간 × 1000은 int를 넘는다 */static void print_pace(long long s, long long m) {    long long p = s * 1000 / m;    printf("%lld:%02lld", p / 60, p % 60);} int main(void) {    int n;    scanf("%d", &n);    for (int i = 0; i < n; i++) scanf("%d", &ds[i]);    for (int i = 0; i < n; i++) scanf("%d", &ts[i]);    long long total_d = 0, total_t = 0;    for (int i = 0; i < n; i++) {        print_speed(ds[i], ts[i]);        putchar(' ');        print_pace(ts[i], ds[i]);        putchar('\n');        total_d += ds[i];        total_t += ts[i];    }    printf("TOTAL ");    print_speed(total_d, total_t);    putchar(' ');    print_pace(total_t, total_d);    putchar('\n');    return 0;}
Craykonmain.cray · 25 lines
속력(m, s){    return Str.Fixed(m / s * 3.6, 2);} // 크레이콘의 / 는 늘 소수까지 나눈다: 버림은 수학.내림으로페이스(s, m){    p = Mathf.Floor(s * 1000 / m);    초 = "" + p % 60;    return Mathf.Quot(p, 60) + ":" + 초.PadLeft(2, "0");} n = Console.ReadLine().ToNumber();거리들 = Console.ReadNumbers();시간들 = Console.ReadNumbers();전체거리 = 0;전체시간 = 0;for (i = 0; i < n; i++){    Console.WriteLine(속력(거리들[i], 시간들[i]) + " " + 페이스(시간들[i], 거리들[i]));    전체거리 += 거리들[i];    전체시간 += 시간들[i];}Console.WriteLine("TOTAL " + 속력(전체거리, 전체시간) + " " + 페이스(전체시간, 전체거리));