0

I set condition that a number greater than surrounding,but it go a false.

for (var i = 0; i + 1 < n; i++) {
    if (arr[i] < arr[i + 1] || arr[i + 1] > arr[i + 2]) {
        count++;
        index1 = i + 1;
    }
}

arr=[1, 2, 3, 6, 5, 4, 7, 8],n=8.

You can see count plus when arr[i+1] smaller than arr[i+2].

this is the picture of problem

Y.H He
  • 21
  • 4

3 Answers3

0

You should use AND condition instead of OR to check value is greater than left and right.

Refer below code:

var arr=[1, 2, 3, 6, 5, 4, 9, 8];
var n=8;
var count = 0;
var pos = [];
for (var i = 0; i + 1 < n; i++) {
    if (arr[i] < arr[i + 1] && arr[i + 1] > arr[i + 2]) {
        count++;
        index1 = i + 1;
        pos.push(index1);
    }
}
console.log("positions: "+pos);
console.log("count: "+count);
Ngoan Tran
  • 1,507
  • 1
  • 13
  • 17
0

The problem is in the condition of ||(OR) since

true || false will result in true 

Also, &&(AND) will result in

true && false will reult in false

So modify your function using "&&" instead of "||"

var arr=[1, 2, 3, 6, 5, 4, 9, 8];
var n=8;
var count = 0;
for (var i = 0; i + 1 < n; i++) {
    if (arr[i] < arr[i + 1] && arr[i + 1] > arr[i + 2]) {
        count++;
        index1 = i + 1;
    }
}

Please refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators for further understanding

dattebayo
  • 1,362
  • 9
  • 4
-1

When i is reaching 6, you test array[i+2] with i+2=8, so the index i+2 is out of bound (the array contains 8 elements, with index starting from 0 to 7). In js, getting a value out of array returns undefined, which is evaluated as a falsy value (evaluated as false).

You can get an explanation about falsy values here:

Community
  • 1
  • 1