How to calculate how many pair of numbers in array

i'm currently in this assignment that bother me how to calculate how many pairs of number within an array

this is what i've been tried before

 function pairNumber (n,ar)
  let numberOfPairs=0
    for(let i =0;i<ar.length;i++){
        for(let j =1;j<ar.length;j++){
            if (ar[i] == ar[j]){
                          console.log([ar[i], ar[j]], '<< ini isinya')
                          console.log(ar[i+1], ar[j+1])

                numberOfPairs++
                ar.splice(i,1)
                ar.splice(j,1)
            }
        }
    }

    if(n%3 == 0){
      numberOfPairs -= 1
      return numberOfPairs
    } else {
      return numberOfPairs
    }
}

console.log(sockMerchant(9,[10,20,20,10,10,30,50,10,20]))
console.log(sockMerchant(10,[1,1,3,1,2,1,3,3,3,3]))

but unfortunately, the return will always be

4
4

the correct answer should be

3
4

for both cases can someone please do help me what I've been missing? thanks you!

Upvotes: 0

Views: 897

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386680

To overcome the quadratic approach with O(n2), you could take an object and count the occurences.

At the end return the sum by counting only the floored half values.

function pairNumber(n, array) {
    var numberOfPairs = 0,
        counts = {};
  
    for (let v of array) {
        if (!counts[v]) counts[v] = 0;
        ++counts[v];
    }

    for (let count of Object.values(counts)) numberOfPairs += count >> 1;

    return numberOfPairs;
}

console.log(pairNumber(9, [10, 20, 20, 10, 10, 30, 50, 10, 20]))
console.log(pairNumber(10, [1, 1, 3, 1, 2, 1, 3, 3, 3, 3]))

Upvotes: 0

Nghi Nguyen
Nghi Nguyen

Reputation: 950

I just do the sort for array first then you just need loop the array 1 time. It's better to control your code

function pairNumber (n,ar){
        let numberOfPairs=0
        let i = 0
        let j = 1

        ar.sort()
         for(let i = 0; i < ar.length; i++){
             if(ar[i] == ar[i++]){
                 numberOfPairs++
                 i+=1
             }
         }
         return numberOfPairs
     }

Upvotes: 1

Subhash Jha
Subhash Jha

Reputation: 64

As this is a simple assignment, I am not going to explain in detail. The issue seems to be in the loop variable initialization. Hint: j=i+1

Upvotes: 0

Related Questions