Skip to content

Instantly share code, notes, and snippets.

@ammardev
Created November 30, 2018 22:30
Show Gist options
  • Save ammardev/07a99951dc11dea5fc6e6630954debe6 to your computer and use it in GitHub Desktop.
Save ammardev/07a99951dc11dea5fc6e6630954debe6 to your computer and use it in GitHub Desktop.
<?php
# Problem 1:
# Functions:
function previousPosition(int $current, int $shift, int $length) {
return ($amount = $current - $shift) < 0 ? $length + $amount : $amount;
}
function rotatePrevious(array $list, int $shift, $startFrom, $replaceWith, $startRoot) {
$currIndex = $startFrom;
$prevIndex = previousPosition($currIndex, $shift, count($list));
$prevElement = $list[$prevIndex];
$list[$prevIndex] = $replaceWith;
if ($prevIndex == $startRoot)
return $list;
return rotatePrevious($list, $shift, $prevIndex, $prevElement, $startRoot);
}
function rotateList(array $list, int $shift) {
$shift = $shift % count($list);
$i = count($list);
while ($i > count($list) - $shift && $i != $shift) {
$i--;
$list = rotatePrevious($list, $shift, $i, $list[$i], $i);
}
return $list;
}
# Function Usage:
while (true) {
echo 'Insert a list of strings: ';
$stringList = fgets(fopen("php://stdin", "r"));
$list = json_decode($stringList);
echo 'Insert the amount of shift (k): ';
$k = fgets(fopen('php://stdin', 'r'));
echo json_encode(rotateList($list, (int)$k)), PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment