HackerRank Sales by Match Problem Solution
In this post, We are going to solve HackerRank Sales by Match Problem.
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
Input Format
The first line contains an integer n, the number of socks represented in ar.
The second line contains n space-separated integers, ar[I], and the colors of the socks in the pile.
Constraints
- 1 < n < 100
- 1 < ar[I] < 100where 0 < I < n
Sample Input
STDIN Function
----- --------
9 n = 9
10 20 20 10 10 30 50 10 20 ar = [10, 20, 20, 10, 10, 30, 50, 10, 20]
Sample Output
3
Sales by Match C Solution
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int main(){
int n, c, total=0;
do{scanf("%d",&n);}while(n<1||n>100);
int col[101];
for(int i=0;i<101;i++) col[i]=0;
for(int a0 = 0; a0 < n; a0++){
do{scanf("%d",&c);}while(c<1||c>100);
col[c]++;
}
for(int i=0;i<101;i++)
if(col[i]!=0)
total+=(col[i]-col[i]%2)/2;
printf("%d", total);
return 0;
}
Sales by Match C++ Solution
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int n, a[100+3];
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
a[x]++;
}
int ans = 0;
for (int i = 1; i <= 100; i++)
ans += a[i] / 2;
cout << ans << endl;
return 0;
}
Sales by Match C Sharp Solution
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {
static void Main(String[] args) {
int n = Convert.ToInt32(Console.ReadLine());
string[] c_temp = Console.ReadLine().Split(' ');
int[] c = Array.ConvertAll(c_temp, Int32.Parse);
Array.Sort(c);
int pairs = 0;
for (int i = 0; i < c.Length - 1; i++)
{
if(c[i] == c[i + 1])
{
pairs++;
i++;
}
}
Console.WriteLine(pairs);
}
}
Sales by Match Java Solution
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* Complete the 'sockMerchant' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. INTEGER n
* 2. INTEGER_ARRAY ar
*/
public static int sockMerchant(int n, List<Integer> ar) {
int pairs = 0;
Map<Integer, Integer> sockColors = new HashMap<>();
ar.stream().forEach(s -> {
sockColors.put(s, sockColors.containsKey(s) ? sockColors.get(s) + 1 : 1);
});
/*
* Imperative
*/
// for (Integer value : sockColors.values()) {
// System.out.println(value);
// pairs += (value % 2 == 0 ? value : value - 1) / 2;
// }
/*
* Declarative
*/
BinaryOperator<Integer> countPairs = new BinaryOperator<Integer>() {
@Override
public Integer apply(Integer accumulator, Integer sockcountforcolor) {
return accumulator += sockcountforcolor % 2 == 0 ? sockcountforcolor
: sockcountforcolor - 1;
}
};
pairs = sockColors.values().stream().reduce(0,countPairs) / 2;
System.out.println(String.format("Number of Pairs : %s", pairs));
return pairs;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = Integer.parseInt(bufferedReader.readLine().trim());
List<Integer> ar = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Integer::parseInt)
.collect(toList());
int result = Result.sockMerchant(n, ar);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}
Sales by Match JavaScript Solution
process.stdin.resume();
process.stdin.setEncoding('ascii');
var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;
process.stdin.on('data', function (data) {
input_stdin += data;
});
process.stdin.on('end', function () {
input_stdin_array = input_stdin.split("\n");
main();
});
function readLine() {
return input_stdin_array[input_currentline++];
}
/////////////// ignore above this line ////////////////////
function main() {
var n = parseInt(readLine());
var c = readLine().split(' ');
c = c.map(Number);
var counted = [];
c.sort(function(a, b) {
return a - b;
});
var result = 0;
for (var i=0; i<n-1; i+=2) {
counted.push[0];
if (c[i]===c[i+1]) {
result++;
counted.push[0];
counted[i] = 1;
counted[i+1] = 1;
}
else {
i--;
}
}
console.log(result);
}
Sales by Match Python Solution
#!/bin/python3
import sys
n = int(input().strip())
colors = input().strip().split()
color_dict = {}
total_pairs = 0
for ind in range(n):
color_dict[colors[ind]] = color_dict.get(colors[ind], 0) + 1
for ind in color_dict:
total_pairs += color_dict[ind]//2
print(total_pairs)
Other Solutions