Check if array can be sorted with one swap of 2 elements

I am trying to write a function that will check if it is possible to sort an array with a single swap of values ​​in the array.

For example: array(1,3,5,3,7)must return true, but array(1,3,5,3,4)must return false.

I tried the following code below, but I am stuck in it:

$noOfIterations = 0;

for($x = 0; $x < count($a)-2; $x++) {

    if($a[$x] > $a[$x+1]) {
        $noOfIterations ++;
    }

}

return $noOfIterations >1; 

// The below solution helped as well.

//$arr = [1, 3, 5, 3, 7];  //[1, 3, 5, 3, 4]
$arr = [1, 3, 5, 3, 4];
$sortedArr = $arr;
sort($sortedArr);
print_r(array_intersect_assoc($arr,$sortedArr));
+4
source share
5 answers

Sort, then compare the original array with the sorted array using array_intersect_assoc () .... if the difference is more than two elements, then the answer is no.

+3
source

This should work for you:

( , sort(). array_map() , . array_filter() , . , 2 , FALSE TRUE)

<?php

    $arr = [1, 3, 5, 3, 7];  //[1, 3, 5, 3, 4]
    $sortedArr = $arr;
    sort($sortedArr);

    $filtered = array_filter(
        array_map(function($v1, $v2){
            return ($v1 == $v2 ?FALSE:TRUE);
        }, $arr, $sortedArr)
    );

    var_dump(count($filtered) > 2 ? FALSE : TRUE);

?>

:

TRUE  //FALSE
+6

, , . . , , , . , 3 4. , . , . , .

+1

, ?

This may help if I know why.

Try this, it works for your two arrays of examples.

function swap($array){
  $prev = 0;
  $count = 0;
  foreach($array as $val){
    if($val < $prev){
       $count++;
    }
    else{
      $prev = $val;
    }
  }
  if($count < 2){return(true);}else{return(false);}
}
0
source

My answer is php.

function oneSwap($A){

  $count=count($A);
  $swaps=0;
  $curr_max = 0;
  $res = false;
  for($i = 0; $i <= $count; $i++) {
    if(isset($A[$i+1])){
      if(($A[$i] >= $A[$i + 1]) && $curr_max >= $A[$i+1]){
        $swaps++;
      }

      if($A[$i] >= $A[$i +1]){
          $curr_max = $A[$i];
      }
    }

  }

  if(($swaps == 1) || ($swaps == 0 && $curr_max ==0)){
    $res = true;
    echo $res;
  } 
} 

oneSwap([3,1,2,8]);
oneSwap([1,2,3]);
oneSwap([1,5,3,3,7]);
oneSwap([3,2,1,8]);
oneSwap([2,1,1,2]);
0
source

Source: https://habr.com/ru/post/1584138/


All Articles