{ }codelper
returning several valuesP0428

Hall chairs numbered in a zigzag

The chairs in a hall stand in rows of w chairs each.
The rows are row 1, row 2, … from the front, and the places in a row are place 1, place 2, …, place w from the left.
The chairs are numbered from 1 in a zigzag.
Row 1 gets numbers 1 to w from its left end (place 1) going right.
Row 2 gets numbers w + 1 to 2w from its right end (place w) going left.
The following rows continue the same way: odd-numbered rows are numbered from place 1 going right, even-numbered rows from place w going left.
There are as many rows as needed.
The first line gives w and the number of questions q, separated by a single space.
Each of the next q lines gives two chair numbers a and b, separated by a single space.
If chair a is in row r1, place c1 and chair b is in row r2, place c2, the number of steps between the two chairs is |r1 − r2| + |c1 − c2|.
For each question, in the order given, print the number of steps on one line.
If a and b are equal, the number of steps is 0.
Try writing a function that receives one chair number and returns two values together: its row and its place (grading looks only at the output).

Input
The first line holds integers w and q (1 ≤ w ≤ 1,000,000,000, 1 ≤ q ≤ 1,000); the next q lines hold integers a and b (1 ≤ a, b ≤ 1,000,000,000)
Output
One line with the number of steps per question
Example 1 · stdin
4 4
1 8
4 5
3 10
6 6
stdout
1
1
3
0
Example 2 · stdin
1 2
1 1000000000
7 3
stdout
999999999
4
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

From one chair number you need two values: the row and the place.
Languages differ in how a function returns two values together.
Python returns the tuple return row, col and receives it with r1, c1 = seat(a, w).
JavaScript returns the array return [row, col] and unpacks it with const [r1, c1] = seat(a, w); TypeScript writes the return type as the tuple [number, number].
C# returns the named tuple (int row, int col) and unpacks it with var (r1, c1) = Seat(a, w).
C++ receives a std::pair<int, int> with auto [r1, c1] = seat(a, w); (C++17).
Java returns only one value, so it bundles them in record Seat(int row, int col) {} and reads s1.row().
C also returns only one value, but it can return a whole struct, so it returns struct seat { int row; int col; } and reads s1.row.
Craykon returns the list return [row, col]; and reads it as s1[0], s1[1].
The arithmetic is the same everywhere.
p, the remainder of (k − 1) divided by w, is the chair's position in its row (from 0); the row is the quotient of (k − 1) divided by w, plus 1; the place is p + 1 in an odd row and w − p in an even row.
In example 1, chair 8 is in row 2, place 1, and chair 10 is in row 3, place 2.
Trap one: forgetting that numbers start at 1 and computing k // w + 1 and k % w pushes the chair at the end of a row (a multiple of w, like 4 or 8) into the next row.
Example 1 becomes 3 1 3 0.
Trap two: / in JavaScript, TypeScript and Craykon divides into decimals.
Using (k - 1) / w + 1 as it is makes a row like 2.75, and example 1 becomes 1.75 3.25 2.75 0 in JavaScript.
JS/TS cut it down with Math.floor, and Craykon uses Mathf.Quot(k - 1, w).
Python's // and / between ints in Java, C#, C and C++ give the quotient.
Trap three: forgetting that even rows start from the right and counting every row from the left puts chair 8 in row 2, place 4, and example 1 becomes 4 4 3 0.
Trap four: mirroring the place in an even row as w - (p + 1) is off by one.
The c-th place from the left is the (w + 1 − c)-th from the right, so the right value is w − p.
Example 1 becomes 2 2 3 0.
Trap five: writing return row, col; in JavaScript as in Python makes it the comma operator, so only the place comes back.
Unpacking that with const [r1, c1] = ... cannot unpack a number, and example 1 stops with a TypeError.
TypeScript's type check rejects the line with TS2695 (left side of the comma operator is unused) and TS2322 (a number is not assignable to [number, number]).
The row difference is at most the quotient of (one billion − 1) divided by w and the place difference at most w − 1, so the number of steps is at most 999,999,999 (example 2: w = 1, chairs 1 and one billion) and a 32-bit int is enough in every language.

Pythonmain.py · 16 lines
def seat(k, w):    """k번 의자의 (줄, 칸)을 돌려준다. 홀수 줄은 왼쪽부터, 짝수 줄은 오른쪽부터 번호가 붙는다."""    row = (k - 1) // w + 1    p = (k - 1) % w  # 그 줄에서 몇 번째 의자인지(0부터)    col = p + 1 if row % 2 == 1 else w - p    return row, col  w, q = map(int, input().split())out = []for _ in range(q):    a, b = map(int, input().split())    r1, c1 = seat(a, w)    r2, c2 = seat(b, w)    out.append(str(abs(r1 - r2) + abs(c1 - c2)))print("\n".join(out))
JavaScriptmain.js · 19 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n"); // k번 의자의 [줄, 칸]을 돌려준다. 홀수 줄은 왼쪽부터, 짝수 줄은 오른쪽부터 번호가 붙는다function seat(k, w) {  const row = Math.floor((k - 1) / w) + 1; // / 는 소수까지 나누니 버린다  const p = (k - 1) % w; // 그 줄에서 몇 번째 의자인지(0부터)  const col = row % 2 === 1 ? p + 1 : w - p;  return [row, col];} const [w, q] = lines[0].trim().split(" ").map(Number);const out = [];for (let i = 1; i <= q; i++) {  const [a, b] = lines[i].trim().split(" ").map(Number);  const [r1, c1] = seat(a, w);  const [r2, c2] = seat(b, w);  out.push(Math.abs(r1 - r2) + Math.abs(c1 - c2));}console.log(out.join("\n"));
TypeScriptmain.ts · 20 lines
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n"); // k번 의자의 [줄, 칸]을 돌려준다. 홀수 줄은 왼쪽부터, 짝수 줄은 오른쪽부터 번호가 붙는다function seat(k: number, w: number): [number, number] {  const row = Math.floor((k - 1) / w) + 1; // / 는 소수까지 나누니 버린다  const p = (k - 1) % w; // 그 줄에서 몇 번째 의자인지(0부터)  const col = row % 2 === 1 ? p + 1 : w - p;  return [row, col];} const [w, q] = lines[0].trim().split(" ").map(Number);const out: string[] = [];for (let i = 1; i <= q; i++) {  const [a, b] = lines[i].trim().split(" ").map(Number);  const [r1, c1] = seat(a, w);  const [r2, c2] = seat(b, w);  out.push(String(Math.abs(r1 - r2) + Math.abs(c1 - c2)));}console.log(out.join("\n"));
JavaMain.java · 31 lines
import java.io.*;import java.util.StringTokenizer; public class Main {    // Java 메서드는 값 하나만 돌려주니 record로 묶는다    record Seat(int row, int col) {}     // k번 의자의 (줄, 칸)을 돌려준다. 홀수 줄은 왼쪽부터, 짝수 줄은 오른쪽부터 번호가 붙는다    static Seat seat(int k, int w) {        int row = (k - 1) / w + 1;        int p = (k - 1) % w; // 그 줄에서 몇 번째 의자인지(0부터)        int col = row % 2 == 1 ? p + 1 : w - p;        return new Seat(row, col);    }     public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        StringTokenizer st = new StringTokenizer(in.readLine());        int w = Integer.parseInt(st.nextToken());        int q = Integer.parseInt(st.nextToken());        StringBuilder out = new StringBuilder();        for (int i = 0; i < q; i++) {            st = new StringTokenizer(in.readLine());            Seat s1 = seat(Integer.parseInt(st.nextToken()), w);            Seat s2 = seat(Integer.parseInt(st.nextToken()), w);            int d = Math.abs(s1.row() - s2.row()) + Math.abs(s1.col() - s2.col());            out.append(d).append('\n');        }        System.out.print(out);    }}
C#Main.cs · 30 lines
using System;using System.Text; class Program{    // k번 의자의 (줄, 칸)을 튜플로 돌려준다. 홀수 줄은 왼쪽부터, 짝수 줄은 오른쪽부터 번호가 붙는다    static (int row, int col) Seat(int k, int w)    {        int row = (k - 1) / w + 1;        int p = (k - 1) % w; // 그 줄에서 몇 번째 의자인지(0부터)        int col = row % 2 == 1 ? p + 1 : w - p;        return (row, col);    }     static void Main()    {        string[] first = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries);        int w = int.Parse(first[0]);        int q = int.Parse(first[1]);        var sb = new StringBuilder();        for (int i = 0; i < q; i++)        {            string[] parts = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries);            var (r1, c1) = Seat(int.Parse(parts[0]), w);            var (r2, c2) = Seat(int.Parse(parts[1]), w);            sb.Append(Math.Abs(r1 - r2) + Math.Abs(c1 - c2)).Append('\n');        }        Console.Write(sb);    }}
C++main.cpp · 23 lines
#include <cstdlib>#include <iostream>#include <utility> // k번 의자의 (줄, 칸)을 돌려준다. 홀수 줄은 왼쪽부터, 짝수 줄은 오른쪽부터 번호가 붙는다std::pair<int, int> seat(int k, int w) {    int row = (k - 1) / w + 1;    int p = (k - 1) % w; // 그 줄에서 몇 번째 의자인지(0부터)    int col = row % 2 == 1 ? p + 1 : w - p;    return {row, col};} int main() {    std::ios::sync_with_stdio(false);    int w, q, a, b;    std::cin >> w >> q;    for (int i = 0; i < q; i++) {        std::cin >> a >> b;        auto [r1, c1] = seat(a, w);        auto [r2, c2] = seat(b, w);        std::cout << std::abs(r1 - r2) + std::abs(c1 - c2) << '\n';    }}
Cmain.c · 29 lines
#include <stdio.h>#include <stdlib.h> /* C 함수는 값 하나만 돌려주니 줄과 칸을 구조체 하나로 묶어 돌려준다 */struct seat {    int row;    int col;}; /* k번 의자의 줄과 칸. 홀수 줄은 왼쪽부터, 짝수 줄은 오른쪽부터 번호가 붙는다 */static struct seat find_seat(int k, int w) {    struct seat s;    int p = (k - 1) % w; /* 그 줄에서 몇 번째 의자인지(0부터) */    s.row = (k - 1) / w + 1;    s.col = s.row % 2 == 1 ? p + 1 : w - p;    return s;} int main(void) {    int w, q, a, b;    if (scanf("%d %d", &w, &q) != 2) return 0;    for (int i = 0; i < q; i++) {        scanf("%d %d", &a, &b);        struct seat s1 = find_seat(a, w);        struct seat s2 = find_seat(b, w);        printf("%d\n", abs(s1.row - s2.row) + abs(s1.col - s2.col));    }    return 0;}
Craykonmain.cray · 23 lines
// k번 의자의 [줄, 칸]을 목록으로 돌려준다. 홀수 줄은 왼쪽부터, 짝수 줄은 오른쪽부터 번호가 붙는다의자자리(k, w){    row = Mathf.Quot(k - 1, w) + 1; // / 는 소수까지 나누니 몫을 쓴다    p = (k - 1) % w; // 그 줄에서 몇 번째 의자인지(0부터)    col = p + 1;    if (row % 2 == 0)    {        col = w - p;    }    return [row, col];} 첫줄 = Console.ReadNumbers();w = 첫줄[0];q = 첫줄[1];for (i = 0; i < q; i++){    쌍 = Console.ReadNumbers();    s1 = 의자자리(쌍[0], w);    s2 = 의자자리(쌍[1], w);    Console.WriteLine(Mathf.Abs(s1[0] - s2[0]) + Mathf.Abs(s1[1] - s2[1]));}