Skip to content

Instantly share code, notes, and snippets.

@allucardster
Last active January 13, 2020 22:31
Show Gist options
  • Save allucardster/0150d8b5ef208262ab684b8b15134de3 to your computer and use it in GitHub Desktop.
Save allucardster/0150d8b5ef208262ab684b8b15134de3 to your computer and use it in GitHub Desktop.
<?php
/*
Rotate an array to the right by a given number of steps.
*/
function cyclicRotation(array $arr, int $k): array
{
if (empty($arr)) {
return $arr;
}
for($i = 0; $i < $k; $i++) {
$arr = array_merge([array_pop($arr)], $arr);
}
return $arr;
}
$test = [
[
[3, 8, 9, 7, 6],
3,
], // Result [9, 7, 6, 3, 8]
[
[0, 0, 0],
1,
], // Result: [0, 0, 0]
[
[1, 2, 3, 4],
4,
], // Result: [1, 2, 3, 4]
];
foreach($test as $params) {
print_r(cyclicRotation(...$params));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment