Last active
November 24, 2021 10:57
-
-
Save barakpinchovski/89e7739641a80719521f61954b90025d to your computer and use it in GitHub Desktop.
PHP solution for https://www.hackerrank.com/challenges/new-year-chaos/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$q = [2,1,5,3,4]; | |
minimumBribes($q); | |
function minimumBribes($q) { | |
$no_ans = 'Too chaotic'; | |
$ans = 0; | |
if (gettype($q) !== 'array' || !count($q)) { | |
return $no_ans; | |
} | |
$len = count($q); | |
end($q); | |
prev($q); | |
while ($currVal = current($q)) { | |
$currKey = key($q) + 1; | |
$positionDiff = $currVal - $currKey; | |
if ($positionDiff > 2) { | |
echo $no_ans . PHP_EOL; | |
return; | |
} | |
elseif ($positionDiff > 0) { | |
shift_arr_values($q, key($q), key($q) + $positionDiff); | |
$ans += $positionDiff; | |
} | |
else { | |
prev($q); | |
} | |
} | |
echo $ans . PHP_EOL; | |
return; | |
} | |
function shift_arr_values(&$arr, $i, $j) { | |
$temp = $arr[$i]; | |
for ($s = $i; $s < $j; $s++) { | |
$arr[$s] = $arr[$s + 1]; | |
} | |
$arr[$j] = $temp; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment