{ }codelper
reversing listsremainderP0408

Reversing bracelet beads across the clasp

A bracelet has n beads strung in a ring.
Starting from the place right after the clasp and going clockwise, the places are numbered 1, 2, …, n.
After place n comes place 1 again.
The place numbers never change; only the beads move between places.
A command s k selects k consecutive places going clockwise from place s.
The selected places are s, s + 1, …, and after place n they continue from place 1.
Then the order of the beads in those k places is reversed.
The beads in the first and the k-th selected place swap, the beads in the second and the (k − 1)-th selected place swap, and so on.
If k = 1, nothing changes.
If k = n, every place is selected, but the result can still depend on the starting place s.
For example, with n = 6 and beads abcdef from place 1, the command 5 4 turns e, f, a, b in places 5, 6, 1, 2 into b, a, f, e, giving fecdba.
Carry out the q commands in the given order, then print the beads from place 1 to place n.

Input
The first line gives n and q separated by one space.
The second line gives the beads in places 1 to n as n lowercase English letters with no spaces.
Each of the next q lines gives the s and k of one command, separated by one space.
1 ≤ n ≤ 1,000, 1 ≤ q ≤ 1,000, 1 ≤ s ≤ n, 1 ≤ k ≤ n.
Several beads may have the same letter
Output
One line: after all commands, the n bead letters from place 1 to place n, written together with no spaces
Example 1 · stdin
6 3
abcdef
5 4
2 6
3 1
stdout
efabdc
Example 2 · stdin
4 2
ring
4 2
2 4
stdout
igrn
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

This problem accepts all 8 languages.
Every language has a ready tool for reversing a range, but they all stop at the end of the list and never wrap around the ring.
So the reference solutions either unroll the ring or count places as (s + i) % n.
Python unrolls it with line = a[s:] + a[:s] so place s comes first, reverses the first k with line[:k] = line[:k][::-1], and turns it back.
C++ does the same with std::rotate and std::reverse(b.begin(), b.begin() + k), and Java with Collections.rotate(list, -s) and Collections.reverse(list.subList(0, k)).
subList is a view of the original list, so reversing it changes the original.
JavaScript, TypeScript, C# and Craykon copy the k beads at places (s + i) % n into a new array, reverse it (JS/TS part.reverse(), C# Array.Reverse(part, 0, k), Craykon part.Reverse()) and put them back in the same places.
JS reverse() does not make a new array; it reverses that array itself.
C swaps one pair at a time from the two ends i and j, moving towards the middle.
Strings cannot be changed one character at a time in Python, JS, TS, Java, C# and Craykon, so they are turned into a list of characters and joined at the end with "".join, join(""), Java StringBuilder, new string(...) or Craykon Join("").
Trap one: cutting k items starting at s straight from the list, without unrolling the ring, stops at the end when s + k is larger than n.
Python a[s:s + k] and JS slice quietly cut a shorter piece, so example 1 gives aefdcb; Java subList throws IndexOutOfBoundsException.
Trap two: when k = n it is tempting to reverse the whole list.
Starting at place s moves the axis of the reversal, so treating it like a.reverse() makes example 1 give abdcef.
Trap three: when swapping from both ends, moving j back with (j - 1) % n gives n − 1 for j = 0 only in Python; the % of C, C++, Java, C#, JS, TS and Craykon gives -1.
Java stops with ArrayIndexOutOfBoundsException on example 1.
Write (j - 1 + n) % n as the C solution does.
Trap four: languages give the end of a range differently.
The end of a Python slice [:k], Java subList(0, k) and C++ std::reverse(first, last) is not included, and the third value of C# Array.Reverse(array, index, length) is a count, not an end place.
Passing begin() + k - 1 in C++ to point at the last item reverses only k − 1 items, so example 1 gives efadcb.
Trap five: when swapping from both ends, swap only k / 2 times.
Swapping k times goes past the middle and swaps every pair back, so whatever the commands, the original bracelet abcdef comes out.

Pythonmain.py · 16 lines
import sys data = sys.stdin.read().split()n, q = int(data[0]), int(data[1])beads = list(data[2])  # 문자열은 고칠 수 없어서 글자 목록으로 바꾼다 for t in range(q):    s, k = int(data[3 + 2 * t]) - 1, int(data[4 + 2 * t])    # s번 자리가 맨 앞에 오도록 고리를 돌려 편다    line = beads[s:] + beads[:s]    # 앞의 k개만 뒤집는다. 슬라이스의 끝 k는 들어가지 않는다    line[:k] = line[:k][::-1]    # 다시 돌려서 1번 자리를 맨 앞으로    beads = line[n - s:] + line[:n - s] print("".join(beads))
JavaScriptmain.js · 16 lines
const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter((w) => w !== "");const n = Number(data[0]);const q = Number(data[1]);const beads = [...data[2]]; // 문자열은 한 글자씩 고칠 수 없어서 글자 배열로 바꾼다 for (let t = 0; t < q; t++) {  const s = Number(data[3 + 2 * t]) - 1;  const k = Number(data[4 + 2 * t]);  // 고리를 따라 k자리를 차례로 꺼낸다. (s + i) % n이 n을 넘으면 앞으로 돌아온다  const part = [];  for (let i = 0; i < k; i++) part.push(beads[(s + i) % n]);  part.reverse(); // 배열 자체를 뒤집는다  for (let i = 0; i < k; i++) beads[(s + i) % n] = part[i];} console.log(beads.join(""));
TypeScriptmain.ts · 16 lines
const data: string[] = require("fs").readFileSync(0, "utf8").split(/\s+/).filter((w: string) => w !== "");const n: number = Number(data[0]);const q: number = Number(data[1]);const beads: string[] = [...data[2]]; // 문자열은 한 글자씩 고칠 수 없어서 글자 배열로 바꾼다 for (let t = 0; t < q; t++) {  const s = Number(data[3 + 2 * t]) - 1;  const k = Number(data[4 + 2 * t]);  // 고리를 따라 k자리를 차례로 꺼낸다. (s + i) % n이 n을 넘으면 앞으로 돌아온다  const part: string[] = [];  for (let i = 0; i < k; i++) part.push(beads[(s + i) % n]);  part.reverse(); // 배열 자체를 뒤집는다  for (let i = 0; i < k; i++) beads[(s + i) % n] = part[i];} console.log(beads.join(""));
JavaMain.java · 34 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.StringTokenizer; public class Main {    public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        StringTokenizer first = new StringTokenizer(in.readLine());        int n = Integer.parseInt(first.nextToken());        int q = Integer.parseInt(first.nextToken());        List<Character> beads = new ArrayList<>();        for (char c : in.readLine().trim().toCharArray()) beads.add(c);         for (int t = 0; t < q; t++) {            StringTokenizer st = new StringTokenizer(in.readLine());            int s = Integer.parseInt(st.nextToken()) - 1;            int k = Integer.parseInt(st.nextToken());            // s번 자리가 맨 앞에 오도록 왼쪽으로 s칸 돌린다            Collections.rotate(beads, -s);            // subList(0, k)는 0 ~ k-1번이다(끝 k는 들어가지 않는다). 그 부분을 제자리에서 뒤집는다            Collections.reverse(beads.subList(0, k));            // 다시 오른쪽으로 s칸 돌려 제자리로            Collections.rotate(beads, s);        }         StringBuilder out = new StringBuilder();        for (char c : beads) out.append(c);        System.out.println(out);    }}
C#Main.cs · 27 lines
using System; class Program{    static void Main()    {        string[] first = Console.ReadLine().Trim().Split(' ');        int n = int.Parse(first[0]);        int q = int.Parse(first[1]);        char[] beads = Console.ReadLine().Trim().ToCharArray(); // string은 고칠 수 없어서 char[]로 바꾼다        char[] part = new char[n];         for (int t = 0; t < q; t++)        {            string[] p = Console.ReadLine().Trim().Split(' ');            int s = int.Parse(p[0]) - 1;            int k = int.Parse(p[1]);            // 고리를 따라 k자리를 차례로 꺼낸다. (s + i) % n이 n을 넘으면 앞으로 돌아온다            for (int i = 0; i < k; i++) part[i] = beads[(s + i) % n];            // Array.Reverse(배열, 시작, 개수): 셋째 값은 끝 자리가 아니라 개수다            Array.Reverse(part, 0, k);            for (int i = 0; i < k; i++) beads[(s + i) % n] = part[i];        }         Console.WriteLine(new string(beads));    }}
C++main.cpp · 26 lines
#include <algorithm>#include <iostream>#include <string> int main() {    std::ios::sync_with_stdio(false);    std::cin.tie(nullptr);    int n, q;    std::string beads;    std::cin >> n >> q >> beads;     for (int t = 0; t < q; t++) {        int s, k;        std::cin >> s >> k;        s -= 1;        // s번 자리가 맨 앞에 오도록 돌린다(beads[s]가 새 맨 앞)        std::rotate(beads.begin(), beads.begin() + s, beads.end());        // [begin, begin + k): 끝 반복자는 들어가지 않으므로 k개다        std::reverse(beads.begin(), beads.begin() + k);        // 다시 돌려 1번 자리를 맨 앞으로        std::rotate(beads.begin(), beads.begin() + (n - s), beads.end());    }     std::cout << beads << "\n";    return 0;}
Cmain.c · 26 lines
#include <stdio.h> int main(void) {    int n, q;    static char beads[1001];    if (scanf("%d %d", &n, &q) != 2) return 0;    scanf("%1000s", beads);     for (int t = 0; t < q; t++) {        int s, k;        scanf("%d %d", &s, &k);        int i = s - 1;           /* 구간의 맨 앞 자리(0부터) */        int j = (s - 1 + k - 1) % n; /* 구간의 맨 뒤 자리 */        /* 양 끝에서 한 쌍씩 바꾸며 가운데로 모인다. k / 2번이면 다 바뀐다 */        for (int m = 0; m < k / 2; m++) {            char tmp = beads[i];            beads[i] = beads[j];            beads[j] = tmp;            i = (i + 1) % n;            j = (j - 1 + n) % n; /* j - 1은 -1이 될 수 있어서 n을 더한다 */        }    }     printf("%s\n", beads);    return 0;}
Craykonmain.cray · 29 lines
첫줄 = Console.ReadLine().Trim().Split(" ");n = 첫줄[0].ToNumber();q = 첫줄[1].ToNumber();// 문자열은 한 글자씩 고칠 수 없어서 글자 목록으로 바꾼다구슬 = [];foreach (c in Console.ReadLine().Trim()){    구슬.Add(c);} for (t = 0; t < q; t++){    p = Console.ReadLine().Trim().Split(" ");    s = p[0].ToNumber() - 1;    k = p[1].ToNumber();    // 고리를 따라 k자리를 차례로 꺼낸다. (s + i) % n이 n을 넘으면 앞으로 돌아온다    조각 = [];    for (i = 0; i < k; i++)    {        조각.Add(구슬[(s + i) % n]);    }    조각.Reverse();    for (i = 0; i < k; i++)    {        구슬[(s + i) % n] = 조각[i];    }} Console.WriteLine(구슬.Join(""));