Skip to content

Instantly share code, notes, and snippets.

@HoangPV
Last active July 30, 2017 21:39
Show Gist options
  • Save HoangPV/493c36291413bbbb9b28395c5524542f to your computer and use it in GitHub Desktop.
Save HoangPV/493c36291413bbbb9b28395c5524542f to your computer and use it in GitHub Desktop.
check whether an array can be turn to non-descending order by a single swap 2 elements
<?php
/**
* check whether an array can be turn to non-descending order by a single swap 2 elements
*
* @param array $a
* @return bool
* @author Phan Vu Hoang <vu-hoang.phan@ekino.com>
*/
function solution($a)
{
$a1 = $a;
asort($a);
$flag = true;
foreach ($a as $key => $value) {
if ($value != $a1[$key]) {
$flag = false;
}
}
if ($flag) {
return true;
} else {
$result = array_diff_assoc($a1, $a);
return (count($result) == 2) ? true : false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment