{ }codelper
slicing listsP0284

Showing one page of a board

A board has n posts and shows k posts per page. The first line gives n, k and p separated by single spaces. The second line gives the n post numbers in the order they appear on screen, separated by single spaces. Page 1 shows the first k posts, page 2 shows the next k posts, and later pages continue the same way. The last page shows only the posts that are left, so it may have fewer than k. Print the post numbers on page p in the given order, separated by single spaces, on one line.

Input
1 ≤ n ≤ 1,000, 1 ≤ k ≤ 1,000, 1 ≤ post number ≤ 1,000,000 (integers).
p is at least 1 and page p has at least one post (1 ≤ p and (p - 1) × k < n)
Output
The post numbers on page p on one line, as plain digits without commas
Example 1 · stdin
7 3 2
70 60 50 40 30 20 10
stdout
40 30 20
Example 2 · stdin
7 3 3
70 60 50 40 30 20 10
stdout
10
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 first post of page p sits at position start = (p - 1) * k, counting from 0.
You cut k items from there, but in some languages the second value of a slice is the end position and in others it is a count.
End position (that position is not included): Python posts[start:start + k], JS/TS posts.slice(start, start + k), Java posts.subList(start, end), C++ std::vector<int>(posts.begin() + start, posts.begin() + end).
Count: C# posts.GetRange(start, count), Craykon posts.GetRange(start, count).
C has no slicing, so loop from start up to just before end.
The biggest difference is when the end runs past the list, as on the last page.
Python and JS/TS quietly cut only what exists.
Java subList stops with IndexOutOfBoundsException, C# GetRange with ArgumentException, and Craykon GetRange also stops, saying the cut is outside the list.
C and C++ do not check and read values outside the list.
So in those languages clamp first with end = min(start + k, n) or count = min(k, n - start).
Three traps: (1) Page numbers start at 1, so starting at p * k shows the page after.
(2) Putting a count where an end position belongs, like JS slice(start, k), always gives an empty list from page 2 on, because start is at least k.
(3) The end position is not included, so writing start + k - 1 drops one post.

Pythonmain.py · 5 lines
n, k, p = map(int, input().split())posts = list(map(int, input().split()))start = (p - 1) * k               # p쪽의 첫 게시물이 있는 자리(0부터)page = posts[start:start + k]     # 끝이 목록 밖이어도 있는 데까지만 자른다print(*page)
JavaScriptmain.js · 6 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n");const [n, k, p] = lines[0].trim().split(/\s+/).map(Number);const posts = lines[1].trim().split(/\s+/).map(Number);const start = (p - 1) * k; // p쪽의 첫 게시물이 있는 자리(0부터)const page = posts.slice(start, start + k); // slice(시작, 끝) — 끝이 목록 밖이어도 있는 데까지만console.log(page.join(" "));
TypeScriptmain.ts · 7 lines
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");const [n, k, p]: number[] = lines[0].trim().split(/\s+/).map(Number);const posts: number[] = lines[1].trim().split(/\s+/).map(Number);const start: number = (p - 1) * k; // p쪽의 첫 게시물이 있는 자리(0부터)const page: number[] = posts.slice(start, start + k); // slice(시작, 끝) — 끝이 목록 밖이어도 있는 데까지만console.log(page.join(" "));
JavaMain.java · 23 lines
import java.util.ArrayList;import java.util.List;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(), p = sc.nextInt();        List<Integer> posts = new ArrayList<>();        for (int i = 0; i < n; i++) posts.add(sc.nextInt());         int start = (p - 1) * k;            // p쪽의 첫 게시물이 있는 자리(0부터)        int end = Math.min(start + k, n);   // subList는 끝이 목록 밖이면 예외라서 n으로 막는다        List<Integer> page = posts.subList(start, end);         StringBuilder out = new StringBuilder();        for (int x : page) {            if (out.length() > 0) out.append(' ');            out.append(x);        }        System.out.println(out);    }}
C#Main.cs · 19 lines
using System;using System.Collections.Generic; class Program{    static void Main()    {        string[] head = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries);        int n = int.Parse(head[0]), k = int.Parse(head[1]), p = int.Parse(head[2]);        var posts = new List<int>();        foreach (string s in Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries))            posts.Add(int.Parse(s));         int start = (p - 1) * k;               // p쪽의 첫 게시물이 있는 자리(0부터)        int count = Math.Min(k, n - start);    // GetRange(시작, 개수)는 목록 밖이면 예외라서 남은 수로 막는다        List<int> page = posts.GetRange(start, count);        Console.WriteLine(string.Join(" ", page));    }}
C++main.cpp · 21 lines
#include <algorithm>#include <iostream>#include <vector> int main() {    int n, k, p;    std::cin >> n >> k >> p;    std::vector<int> posts(n);    for (int& x : posts) std::cin >> x;     int start = (p - 1) * k;            // p쪽의 첫 게시물이 있는 자리(0부터)    int end = std::min(start + k, n);   // 마지막 쪽은 남은 게시물까지만    // 반복자 두 개(시작, 끝)로 새 vector를 만든다    std::vector<int> page(posts.begin() + start, posts.begin() + end);     for (std::size_t i = 0; i < page.size(); i++) {        if (i > 0) std::cout << ' ';        std::cout << page[i];    }    std::cout << '\n';}
Cmain.c · 20 lines
#include <stdio.h> int main(void) {    int n, k, p;    static int posts[1000];    if (scanf("%d %d %d", &n, &k, &p) != 3) return 0;    for (int i = 0; i < n; i++) {        if (scanf("%d", &posts[i]) != 1) return 0;    }    int start = (p - 1) * k;   // p쪽의 첫 게시물이 있는 자리(0부터)    int end = start + k;       // 끝 자리(이 자리는 넣지 않는다)    if (end > n) end = n;      // 마지막 쪽은 남은 게시물까지만    // C에는 자르기가 없어서 start부터 end 앞까지 직접 돈다    for (int i = start; i < end; i++) {        if (i > start) putchar(' ');        printf("%d", posts[i]);    }    putchar('\n');    return 0;}
Craykonmain.cray · 9 lines
head = Console.ReadNumbers();n = head[0];k = head[1];p = head[2];posts = Console.ReadNumbers();start = (p - 1) * k; // p쪽의 첫 게시물이 있는 자리(0부터)count = Mathf.Min(k, n - start); // 부분목록(시작, 개수)은 목록 밖이면 멈추니 남은 수로 막는다page = posts.GetRange(start, count);Console.WriteLine(page);