[Resolvido] Array Rotation - PHP Array Task

  

4
Início do tópico

Write a program that receives an array and number of rotations you have to perform (first element goes at the end).

Print the resulting array.

Examples:

array rotation php array task

2 Respostas
3

My answer:

<?php
 
$array = array_map('intval', explode(' ', readline()));
$rotations = intval(readline());
$count = count($array);
$rotations = $rotations % $count;
 
$newArray = [];
 
for ($i = $rotations; $i < $count; $i++) {
    $newArray[] = $array[$i];
}
 
for ($i = 0; $i < $rotations; $i++) {
    $newArray[] = $array[$i];
}
 
echo implode(' ', $newArray);
2

another solution with array_shift():

<?php
 
$array = array_map('intval', explode(' ', readline()));
$rotations = intval(readline());
 
for ($i = 0; $i < $rotations; $i++) {
    $first = array_shift($array);
    $array[] = $first;
}
 
echo implode(' ', $array);
Partilhar: