Rotate a list

Move every item of a list to the right, wrapping round at the end.

What to build

A program that rotates a list without going through it one step at a time.

Requirements

  • Read a list of numbers, then a number k.
  • Move every item k places to the right. Items that fall off the end come back at the start.
  • Print the result, separated by single spaces.

Input

Two lines: the numbers, then k.

Output

One line.

Constraints

There are from 1 to 100 numbers. k is from 0 to 1000, so it can be larger than the list.

Example

Input:

1 2 3 4 5
2

Output:

4 5 1 2 3

Why it works

Rotating by the length of the list gives the same list, so only the remainder matters. Once k is in range, the answer is two slices of the original placed the other way round.

Examples

Example 1 · Input
1 2 3 4 5
2
Expected output
4 5 1 2 3
Example 2 · Input
7 8
1
Expected output
8 7

Hints

Hint 1

Moving by the length of the list changes nothing, so use k % length.

Hint 2

The last k items come first: slice(length - k), then slice(0, length - k).

Hint 3

Spread both pieces into a new array.

Solution

Show one correct solution (try it yourself first)
const nums = prompt().split(" ").map(Number);
const k = Number(prompt()) % nums.length;
const cut = nums.length - k;
const rotated = [...nums.slice(cut), ...nums.slice(0, cut)];
console.log(rotated.join(" "));

Lesson: Arrays →