{ }codelper
string indexingnegative remainderP0297

A letter tape that turns and flips

There is a tape s with n characters written in a row. Process q commands in the given order. L k takes the first character of the tape and attaches it to the end, k times. R k takes the last character of the tape and attaches it to the front, k times. F reverses the whole tape (the last character comes first). W p c overwrites the p-th character from the front of the current tape with the character c. Q p prints the p-th character from the front of the current tape on one line. The number p counts the first character as 1.
k can be larger than n. The first line gives s, the second line gives q, and each of the next q lines gives one command.
The letters and numbers inside a command are separated by single spaces. For each Q command print one character on its own line, and on the last line print the whole tape after all commands.

Input
s consists of lowercase English letters and digits, and its length n satisfies 1 ≤ n ≤ 10,000.
1 ≤ q ≤ 10,000.
For L and R, 1 ≤ k ≤ 1,000,000,000 (given as plain digits without commas).
For W and Q, 1 ≤ p ≤ n.
The c of W is one lowercase English letter or digit.
There may be no Q command
Output
One character per line for each Q command, then the tape of length n on the last line
Example 1 · stdin
abcdef
10
Q 1
L 2
Q 1
F
Q 1
L 1
Q 1
W 2 x
R 9
Q 6
stdout
a
c
b
a
e
dcbaxe
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

Reading by index is s[i] in Python, JS, TS, C#, C, C++ and Craykon, and s.charAt(i) in Java.
Writing to that position differs by language.
Python s[i] = c raises TypeError, Java has no such syntax, C# and TS give a compile error (read-only), and Craykon stops with 'a string cannot be changed one character at a time'.
JS is the most dangerous: s[i] = c is silently ignored (a TypeError only in strict mode), so the tape stays the same.
So convert to a list of characters you can change: Python list(s), JS and TS [...s], Java toCharArray(), C# ToCharArray(), and in Craykon Add each character to a list.
A C char array and a C++ std::string accept s[i] = c directly.
Instead of really rotating or reversing the tape for every command, keep just two numbers meaning 'character i of the current tape is character (start + direction × i) of the original string'; then each command is a single calculation.
Trap 1: that index can be negative.
Python's % always gives 0 to n − 1, but in C, C++, Java, C#, JS, TS and Craykon -2 % 5 is -2.
In JS and TS tape[-2] is undefined without any error, so that character goes missing (join) or "undefined" is printed (when joined with +); Java, C# and Craykon stop with an error; C and C++ read outside the array.
Use ((x % n) + n) % n or Java Math.floorMod(x, n).
Trap 2: after a flip, 'send the first character to the back' moves the other way in the original string, so the k of L and R must be multiplied by the direction.
Trap 3: a flip must not only change the direction; the start must also move to what is currently the last character.
Trap 4: the p-th character counted by people is index p - 1 counting from 0.
Trap 5: k goes up to a billion, so you cannot rotate one step k times, and adding it unreduced into an int passes 2.1 billion on the third command and wraps around.
Reduce it with k % n first.

Pythonmain.py · 31 lines
import sys lines = sys.stdin.read().split("\n")tape = list(lines[0].strip())  # 문자열은 한 글자씩 고칠 수 없어서 글자 목록으로 바꾼다n = len(tape)q = int(lines[1]) # 띠를 실제로 돌리지 않는다. 지금 띠의 i번 글자(0부터)는 tape[(start + step * i) % n]start, step = 0, 1  def where(i):    return (start + step * i) % n  # Python의 %는 음수에서도 0 ~ n-1을 준다  out = []for line in lines[2:2 + q]:    p = line.split()    if p[0] == "L":        start = where(int(p[1]) % n)    elif p[0] == "R":        start = where(-(int(p[1]) % n))    elif p[0] == "F":        start = where(n - 1)  # 맨 끝 글자가 새 맨 앞        step = -step    elif p[0] == "W":        tape[where(int(p[1]) - 1)] = p[2]    else:        out.append(tape[where(int(p[1]) - 1)])out.append("".join(tape[where(i)] for i in range(n)))print("\n".join(out))
JavaScriptmain.js · 28 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n");const tape = [...lines[0].trim()]; // 문자열은 한 글자씩 고칠 수 없어서 글자 배열로 바꾼다const n = tape.length;const q = Number(lines[1]); // 띠를 실제로 돌리지 않는다. 지금 띠의 i번 글자(0부터)는 tape[(start + step * i) % n]let start = 0, step = 1;// JS의 %는 음수에서 음수를 주므로 n을 더해 한 번 더 나눈다const where = (i) => (((start + step * i) % n) + n) % n; const out = [];for (const line of lines.slice(2, 2 + q)) {  const p = line.trim().split(" ");  if (p[0] === "L") {    start = where(Number(p[1]) % n);  } else if (p[0] === "R") {    start = where(-(Number(p[1]) % n));  } else if (p[0] === "F") {    start = where(n - 1); // 맨 끝 글자가 새 맨 앞    step = -step;  } else if (p[0] === "W") {    tape[where(Number(p[1]) - 1)] = p[2];  } else {    out.push(tape[where(Number(p[1]) - 1)]);  }}out.push(tape.map((_, i) => tape[where(i)]).join(""));console.log(out.join("\n"));
TypeScriptmain.ts · 30 lines
import { readFileSync } from "node:fs"; const lines: string[] = readFileSync(0, "utf8").split("\n");const tape: string[] = [...lines[0].trim()]; // 문자열은 한 글자씩 고칠 수 없어서 글자 배열로 바꾼다const n = tape.length;const q = Number(lines[1]); // 띠를 실제로 돌리지 않는다. 지금 띠의 i번 글자(0부터)는 tape[(start + step * i) % n]let start = 0, step = 1;// TS의 %는 음수에서 음수를 주므로 n을 더해 한 번 더 나눈다const where = (i: number): number => (((start + step * i) % n) + n) % n; const out: string[] = [];for (const line of lines.slice(2, 2 + q)) {  const p = line.trim().split(" ");  if (p[0] === "L") {    start = where(Number(p[1]) % n);  } else if (p[0] === "R") {    start = where(-(Number(p[1]) % n));  } else if (p[0] === "F") {    start = where(n - 1); // 맨 끝 글자가 새 맨 앞    step = -step;  } else if (p[0] === "W") {    tape[where(Number(p[1]) - 1)] = p[2];  } else {    out.push(tape[where(Number(p[1]) - 1)]);  }}out.push(tape.map((_, i) => tape[where(i)]).join(""));console.log(out.join("\n"));
JavaMain.java · 35 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader; public class Main {    static int n, start = 0, step = 1;     // 띠를 실제로 돌리지 않는다. 지금 띠의 i번 글자(0부터)가 있는 원래 자리    static int where(int i) {        return Math.floorMod(start + step * i, n); // %와 달리 음수에서도 0 ~ n-1을 준다    }     public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        char[] tape = in.readLine().trim().toCharArray(); // String은 고칠 수 없어서 char[]로 바꾼다        n = tape.length;        int q = Integer.parseInt(in.readLine().trim());        StringBuilder out = new StringBuilder();        for (int t = 0; t < q; t++) {            String[] p = in.readLine().trim().split(" ");            switch (p[0]) {                case "L" -> start = where(Integer.parseInt(p[1]) % n);                case "R" -> start = where(-(Integer.parseInt(p[1]) % n));                case "F" -> {                    start = where(n - 1); // 맨 끝 글자가 새 맨 앞                    step = -step;                }                case "W" -> tape[where(Integer.parseInt(p[1]) - 1)] = p[2].charAt(0);                default -> out.append(tape[where(Integer.parseInt(p[1]) - 1)]).append('\n');            }        }        for (int i = 0; i < n; i++) out.append(tape[where(i)]);        System.out.println(out);    }}
C#Main.cs · 46 lines
using System;using System.Text; class Program{    static int n, start = 0, step = 1;     // 띠를 실제로 돌리지 않는다. 지금 띠의 i번 글자(0부터)가 있는 원래 자리    static int Where(int i)    {        return ((start + step * i) % n + n) % n; // C#의 %는 음수에서 음수를 준다    }     static void Main()    {        char[] tape = Console.ReadLine().Trim().ToCharArray(); // string은 고칠 수 없어서 char[]로 바꾼다        n = tape.Length;        int q = int.Parse(Console.ReadLine().Trim());        var output = new StringBuilder();        for (int t = 0; t < q; t++)        {            string[] p = Console.ReadLine().Trim().Split(' ');            switch (p[0])            {                case "L":                    start = Where(int.Parse(p[1]) % n);                    break;                case "R":                    start = Where(-(int.Parse(p[1]) % n));                    break;                case "F":                    start = Where(n - 1); // 맨 끝 글자가 새 맨 앞                    step = -step;                    break;                case "W":                    tape[Where(int.Parse(p[1]) - 1)] = p[2][0];                    break;                default:                    output.Append(tape[Where(int.Parse(p[1]) - 1)]).Append('\n');                    break;            }        }        for (int i = 0; i < n; i++) output.Append(tape[Where(i)]);        Console.WriteLine(output);    }}
C++main.cpp · 41 lines
#include <iostream>#include <string> int main() {    std::ios::sync_with_stdio(false);    std::string tape; // std::string은 tape[i] = c로 한 글자씩 고칠 수 있다    int q;    std::cin >> tape >> q;    const int n = static_cast<int>(tape.size());     // 띠를 실제로 돌리지 않는다. 지금 띠의 i번 글자(0부터)는 tape[(start + step * i) % n]    int start = 0, step = 1;    // C++의 %는 음수에서 음수를 주므로 n을 더해 한 번 더 나눈다    auto where = [&](int i) { return ((start + step * i) % n + n) % n; };     std::string out;    for (int t = 0; t < q; t++) {        char cmd, c;        int v;        std::cin >> cmd;        if (cmd == 'L') {            std::cin >> v;            start = where(v % n);        } else if (cmd == 'R') {            std::cin >> v;            start = where(-(v % n));        } else if (cmd == 'F') {            start = where(n - 1); // 맨 끝 글자가 새 맨 앞            step = -step;        } else if (cmd == 'W') {            std::cin >> v >> c;            tape[where(v - 1)] = c;        } else {            std::cin >> v;            out += tape[where(v - 1)];            out += '\n';        }    }    for (int i = 0; i < n; i++) out += tape[where(i)];    std::cout << out << '\n';}
Cmain.c · 45 lines
#include <stdio.h>#include <string.h> static char tape[10001]; /* char 배열은 한 글자씩 고칠 수 있다 */static int n, start = 0, step = 1; /* 띠를 실제로 돌리지 않는다. 지금 띠의 i번 글자(0부터)가 있는 원래 자리 */static int where(int i) {    return ((start + step * i) % n + n) % n; /* C의 %는 음수에서 음수를 준다 */} int main(void) {    int q;    scanf("%10000s %d", tape, &q);    n = (int)strlen(tape);    for (int t = 0; t < q; t++) {        char cmd, c;        int v;        scanf(" %c", &cmd);        switch (cmd) {        case 'L':            scanf("%d", &v);            start = where(v % n);            break;        case 'R':            scanf("%d", &v);            start = where(-(v % n));            break;        case 'F':            start = where(n - 1); /* 맨 끝 글자가 새 맨 앞 */            step = -step;            break;        case 'W':            scanf("%d %c", &v, &c);            tape[where(v - 1)] = c;            break;        default:            scanf("%d", &v);            printf("%c\n", tape[where(v - 1)]);        }    }    for (int i = 0; i < n; i++) putchar(tape[where(i)]);    putchar('\n');    return 0;}
Craykonmain.cray · 50 lines
줄 = Console.ReadLine().Trim();// 문자열은 한 글자씩 고칠 수 없어서 글자 목록으로 바꾼다tape = [];foreach (c in 줄){    tape.Add(c);}n = tape.Count;q = Console.ReadLine().ToNumber(); // 띠를 실제로 돌리지 않는다. 지금 띠의 i번 글자(0부터)는 tape[(start + step * i) % n]start = 0;step = 1; // 크레이콘의 %는 음수에서 음수를 주므로 n을 더해 한 번 더 나눈다자리(i){    return ((start + step * i) % n + n) % n;} for (t = 0; t < q; t++){    p = Console.ReadLine().Trim().Split(" ");    switch (p[0])    {        case "L":            start = 자리(p[1].ToNumber() % n);            break;        case "R":            start = 자리(-(p[1].ToNumber() % n));            break;        case "F":            // 맨 끝 글자가 새 맨 앞            start = 자리(n - 1);            step = -step;            break;        case "W":            tape[자리(p[1].ToNumber() - 1)] = p[2];            break;        default:            Console.WriteLine(tape[자리(p[1].ToNumber() - 1)]);            break;    }}끝 = [];for (i = 0; i < n; i++){    끝.Add(tape[자리(i)]);}Console.WriteLine(끝.Join(""));