How to test a pair of numbers in one array?
like
const arr = [1, 3, 5, 9, 11, 12]
I want to test 1 and 3, 3 and 5, 5 and 9, 9 and 11, 11 and 12.
for (let i= 0; arr.length > i; i++){
for (let j=0; arr.length > j; j++){
console.log(arr[i], arr[j])
}}
How does the douple for loop needs to look like in javascript.
3
Answers
As mentioned by @gog, you can achieve the pair testing in an array with a single loop. Just iterate from 0 to length – 2 and compare arr[i] with arr[i+1].
To do this, use the loop condition i < arr.length – 1. This approach ensures you stop just before the last element, allowing for valid pair comparisons between adjacent elements.
Quite simply using a "sliding window" technique:
You can even generalize it:
You don’t need an inner loop: