skip to Main Content

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


  1. Chosen as BEST ANSWER

    I tried with this approach. it works better for me.

    const ar = [1, 3, 2, 6, 1, 2]
    const copy = [...ar];
    const result = []
    ar.forEach(v => {
      copy.shift()
      copy.forEach(n => {
        if((v+n) % 3 === 0) {
          result.push([v,n])
        }
      });
    });
    
    console.log(result.length)


  2. 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.

    const ar = [1, 3, 2, 6, 1, 2], n = 6, k = 3;
    const list = [];
        
    const filter = (num, index) => {
      for(let i = index; i < n; i++) {
        if((num+ar[i]) %3 === 0){
          list.push([num, ar[i]]);
        }
      }
    }
        
    for(let i = 0; i < n; i++) {
      const val = ar[i]
      filter(val, i+1)
    }
        
    console.log(list); 
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search