PHP: Rotate a list

Move the end of a list to the front, using slices.

What to build

A program that rotates a list to the right.

Requirements

  • Read n and k, then n integers.
  • Rotate the list to the right by k places (the last k items move to the front) and print it separated by spaces. k may be larger than n.

Input

Line 1: n and k. Line 2: n integers.

Output

One line.

Constraints

1 ≤ n ≤ 100; 0 ≤ k ≤ 1000.

Example

Input:

5 2
1 2 3 4 5

Output:

4 5 1 2 3

Why it works

Rotating a full turn changes nothing, so only k % n matters, and two slices put the parts in the new order.

Examples

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

Hints

Hint 1

Rotating by k is the same as rotating by k % n.

Hint 2

array_slice($a, -$k) gives the last k items, and array_slice($a, 0, $n - $k) the rest.

Solution

Show one correct solution (try it yourself first)
<?php
fscanf(STDIN, "%d %d", $n, $k);
$a = array_map('intval', explode(" ", trim(fgets(STDIN))));
$k %= $n;
if ($k > 0) {
    $a = array_merge(array_slice($a, -$k), array_slice($a, 0, $n - $k));
}
echo implode(" ", $a), "\n";

▶ Open this solution in the compiler

Lesson: Arrays →