DEV Community

code & coffee
code & coffee

Posted on

Sales by Match solution in Javascript

Problem:

Image description
There is a large pile of socks that must be paired by color. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
Example
n = 7,
ar = [1,2,1,2,1,3,2]

There is one pair of color 1 and one of color 2. There are three odd socks left, one of each color. The number of pairs is 2.

Function Description

Complete the sockMerchant function in the editor below.

sockMerchant has the following parameter(s):

int n: the number of socks in the pile
int ar[n]: the colors of each sock

Returns

int: the number of pairs

Solution:

The simplest way to solve this problem is by breaking it down into simple steps as follows:

  1. Go through the list of items and sort them by color.
  2. Once we have a collection of items of the same color, we can determine from the collection how many form a pair.

In Javascript we solve that in the following:

  1. Loop through the array and assign unique values to a map. If a value already exists in the map, we will increment the value. The idea is to have a map that shows items and the number of times it appears.

Map(4) { 10 => 4, 20 => 3, 30 => 1, 50 => 1 }

  1. From the map, we can now detemine which forms a pair.
function sockMerchant(n, ar) {   

    //1. Loop through array items and arrange items in a map by unique color

    let mapOfColors = new Map();

    for(let i = 0; i< n ; i++ ){
        // If found, increment the map value
        if(mapOfColors.has(ar[i])){
            let currentVal = mapOfColors.get(ar[i]);
            mapOfColors.set(ar[i], currentVal+1);
        }        
        // If item is not found, add it to map
        else{
            mapOfColors.set(ar[i], 1)
        }        
    }

    //2. From the map, we can now detemine which form a pair

    let pairs = 0; 

    for(let countOfColor of mapOfColors.values() ){
        // Check if it can create complete pairs
        if(countOfColor % 2 === 0){
            pairs += countOfColor/2;
        }else{
            pairs += (countOfColor-1)/2;
        }
    }

    return pairs;
}

const pairs = sockMerchant(9, [10, 20, 20, 10, 10, 30, 50, 10, 20]);
console.log ( pairs);
Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)