Created
September 12, 2019 15:08
-
-
Save barakpinchovski/81e83a5824d193272fd146461ea960fc to your computer and use it in GitHub Desktop.
PHP solution for https://www.hackerrank.com/challenges/minimum-swaps-2/
This file contains 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 | |
echo minimumSwaps($arr); | |
function minimumSwaps($arr) { | |
$swaps = 0; # Default function value | |
if (gettype($arr) !== 'array' || !count($arr)) { | |
return $swaps; | |
} | |
$len = count($arr); | |
while ($currValue = current($arr)) { | |
$currKey = key($arr) + 1; | |
if ($currKey !== $currValue) { | |
$swaps += swap_arr_values($arr, key($arr), $currValue - 1); | |
} | |
else { | |
next($arr); | |
} | |
} | |
return $swaps; | |
} | |
function swap_arr_values(&$arr, $i, $j) { | |
$temp = $arr[$j]; | |
$arr[$j] = $arr[$i]; | |
$arr[$i] = $temp; | |
return 1; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment