You are viewing a single comment's thread. Return to all comments →
Here is my solution in PHP
$original = $arr; $length = count($arr); $decresingIndex = 0; $decreasingLastIndex = 0; $decreasingArray =[]; $max = 0; $output = 'yes'; for ($i=1; $i < $length ; $i++) { if($original[$i] > $original[$i-1]) { continue; } else { //echo $i; $decresingIndex = $i-1; $decreasingArray[] = $original[$i-1]; $max = $original[$i-1]; break; } } for ($i=$decresingIndex+1; $i < $length ; $i++) { if($original[$i-1] > $original[$i]) { $decreasingArray[] = $original[$i]; } else { $decreasingLastIndex = $i-1; break; } } $cc = count($decreasingArray); if($cc == 0) { echo "yes\n"; } else { if($decreasingLastIndex == 0) { if($cc == 2) { echo "yes\n"; echo "swap ". ($decresingIndex + 1)." ". ($decresingIndex + 2)."\n"; } else { echo "yes\n"; echo "reverse ". ($decresingIndex + 1)." ". ($decresingIndex + $cc)."\n"; } } else { if ($original[$decreasingLastIndex+1] > $max) { if($cc == 2) { $output = "yes\n"; $output .= "swap ". ($decresingIndex + 1)." ". ($decresingIndex + 2)."\n"; $val = $original[$decresingIndex+1]; for ($i=$decresingIndex-1; $i >= 0 ; $i--) { if ($original[$i] < $val) { continue; } else { $output = 'no'; break; } } echo $output; } else { $output = "yes\n"; $output .= "reverse ". ($decresingIndex + 1)." ". ($decresingIndex + $cc)."\n"; for ($i=$decresingIndex + $cc; $i < $length-1 ; $i++) { if ((int)$original[$i+1] > (int)$original[$i]) { continue; } else { $output = 'no'; break; } } echo $output; } } else { $output = 'no'; $swapIndex = 0; for ($i=$decresingIndex +1 ; $i < $length ; $i++) { if ($original[$i] > $max) { $output = "yes\n"; $output.= "swap ". ($decresingIndex + 1)." ". ($i)."\n"; $swapIndex = $i; break; } } if ($swapIndex > 0) { for ($i=$swapIndex; $i < $length-1 ; $i++) { if ($original[$i+1] > $original[$i]) { continue; } else { $output = 'no'; break; } } } echo $output; } } }
Seems like cookies are disabled on this browser, please enable them to open this website
Almost Sorted
You are viewing a single comment's thread. Return to all comments →
Here is my solution in PHP