Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count pairs in an array in JavaScript

Tags:

javascript

I'm still a junior at web dev and I am trying to solve this problem. I have to find the number of matching pairs in these arrays:

var ar1 = [10, 20, 20, 10, 10, 30, 50, 10, 20] // return 3 (2 pairs of 10 and 1 pair of 20)
var ar2 = [1, 1, 3, 1, 2, 1, 3, 3, 3, 3] // return 4 (2 pairs of 1 and 2 pairs of 3)

// I started to write my logic below but I'm stuck, could you please help me to solve this problem ?


// The last result I am returning is a filtered array with all the nbs that are superior to 1 and then can't figure out how to get the result of matching pairs :-(

function countPairs(n, ar) {
  const count = {};
  ar.forEach((nb) => (count[nb] = (count[nb] || 0) + 1));
  const values = Object.values(count);
  const filter = values.filter((value) => value > 1);
  return filter;
}

// 9 and 10 are the length of the arrays
console.log(countPairs(9, ar1))
console.log(countPairs(10, ar2))

Thank you very much for your help!

like image 806
OmenIII Avatar asked Dec 22 '19 13:12

OmenIII


People also ask

How do you count pairs in an array?

Naive Approach: Run two nested loops and check every possible pair for the condition where i + j = arr[i] + arr[j]. If the condition is satisfied, then update the count = count + 1. Print the count at the end.

How do you count number of pairs?

= n(n-1) / 2 which is our formula for the number of pairs needed in at least n statements.

What is sum += in JavaScript?

The addition assignment operator ( += ) adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator.

How do I count the number of values in JavaScript?

js | count() Function. The count() function is used to count the number of collections in the element. In JavaScript, the array is first converted to a collection and then the function is applied to the collection. Return Value: Returns the count of the element in that collection.


1 Answers

We can achieve this in O(n) time. Maintain an object which keeps track whether a number have been found before, if it was found before, then it makes up a pair, so we increment the pairs count. If not we make the entry of that number in the object 1

function countPairs(arr) {
    let pairs = 0;
    const obj = {};
    arr.forEach(i => {
        if (obj[i]) {
            pairs += 1;
            obj[i] = 0;
        } else {
            obj[i] = 1;
        }
    });
    return pairs;
}
like image 165
Abito Prakash Avatar answered Sep 18 '22 19:09

Abito Prakash