I would like to find the pair of array values which produces multiple of 3 from the array given, as per given array I got the possible of following when I iterate single time. I am trying to achieve the same. but getting more vales. so finding the correct way to achieve the following:
1. 1+2 = 3
2. 1+2 = 3
3. 3+6 = 9
4. 2+1 = 3
5. 1+2 = 3
for I try like this:
const ar = [1, 3, 2, 6, 1, 2], n = 6, k = 3;
const list = [];
const filter = (num) => {
const v = ar.filter(v => {
if((num+v) %3 === 0){
list.push([num, v]);
}
});
}
for(let i = 0; i < n; i++) {
const val = ar[i]
filter(val)
}
console.log(list);
But gives more pairs[12] than required length. How to handle this? I understood I lost some logic here.
2
Answers
I tried with this approach. it works better for me.
Just pass another value as index to the filter function by incrementing it by 1 so that it will check the multiples from the next number and will not include the numbers below the current selected one.