I'm currently working on a function as described in the tittle, where I need to get and array of X values and see if they get in a perfectly increasing order by removing one and only one of it's elements, the problem is that this must be made in PHP, while the logic seems to be adding up, even tried this on another language successfully, but it doesn't work on PHP probably due to my own limited knowledge, any help is appreciated.
Conditions:
If the array can be ordened by removing one and only one value, return True
.
Arrays with only one element after the change are ordened by default.
Repeated numbers don't count as ordened.
<?php
function SequenciaCrescente($arr, $n){
if($n == 2){
return true;
}
$modify = 0;
for($i=0; $i<$n-1; $i ) {
if($arr[$i] >= $arr[$i 1] || $arr[$i] >= $arr[$i 2]){
$modify ;
}
if($modify > 1)
break;
}
if($arr[$n-2]>=$arr[$n-1])
$modify ;
if($modify > 1)
return false;
return true;
}
$arr = array(1, 2, 3, 4, 5, 3, 5, 6);
$n = sizeof($arr);
if (SequenciaCrescente($arr, $n) == true)
echo "True";
else
echo "False";
?>
Example of arrays it should return True but returns False:
1, 2, 3, 4, 3, 6
and 3, 5, 67, 98, 3
.
CodePudding user response:
Its pretty simple, run the loop to check the sequence, if not in order then increase the counter. Check if the counter is greater than 1, then break the loop. Finally check the last the values applying same logic.
And you are not calling your function, check() is not defined.
function SequenciaCrescente($arr, $n){
$modify = 0;
for($i=0; $i<$n-1; $i ) {
if($arr[$i] >= $arr[$i 1])
$modify ;
if($modify > 1)
break;
}
if($arr[$n-2]>=$arr[$n-1])
$modify ;
if($modify > 1)
return false;
return true;
}
$arr = array(1,3,2,4);
$n = sizeof($arr);
if (SequenciaCrescente($arr, $n) == true)
echo "Yes";
else
echo "No";
CodePudding user response:
Try this solution:
function increasableList($list) {
$barrier_counter = 0;
$temp = $list[0];
for($i=1; $i<count($list); $i ) {
if($temp > $list[$i]) {
$barrier_counter ;
}
else {
$temp = $list[$i];
}
}
if($barrier_counter == 1) {
echo "Yes";
}
else {
echo "No";
}
}
increasableList([1, 2, 3, 1, 4]);