Sock Merchant - Hacker Rank Solution
John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs
of socks with matching colors there are.
For example, there are socks with colors . There is one pair of color and one of color . There are three odd socks left, one of each color. The number of pairs is .
Function Description
Complete the sockMerchant function in the editor below. It must return an integer representing the number of matching pairs of socks that are available.
sockMerchant has the following parameter(s):
- n: the number of socks in the pile
- ar: the colors of each sock
Input Format
The first line contains an integer , the number of socks represented in .
The second line contains space-separated integers describing the colors of the socks in the pile.
The second line contains space-separated integers describing the colors of the socks in the pile.
Constraints
- where
Output Format
Return the total number of matching pairs of socks that John can sell.
Sample Input
9
10 20 20 10 10 30 50 10 20
Sample Output
3
Explanation
John can match three pairs of socks.
Sock Merchant - Hacker Rank Solution
To solve this challenge, we go through each color and count its frequency, . Once we've calculated all the frequencies, we calculate the number of pairs of each kind of sock as (using integer division). Finally, we print the total sum of all pairs of socks.
Problem Setter's code:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin>>n;
int freq[101] = {};
for(int i = 0; i < n; i++) {
int c;
cin >> c;
freq[c]++;
}
int res = 0;
for(int i = 0; i <= 100; i++){
res += freq[i] / 2;
}
cout << res << endl;
return 0;
}
Python 2.7
from itertools import groupby
n = int(raw_input())
c = map(int, raw_input().split())
ans = 0
for val in [len(list(group)) for key, group in groupby(sorted(c))]:
ans = ans + val/2
print ans
Problem Tester's code:
Java
import java.util.*;
class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
HashMap<Integer, Integer> colors = new HashMap<Integer, Integer>();
while(n-- > 0) {
int c = scan.nextInt();
Integer frequency = colors.get(c);
// If new color, add to map
if(frequency == null) {
colors.put(c, 1);
}
else { // Increment frequency of existing color
colors.put(c, frequency + 1);
}
}
scan.close();
// Count and print the number of pairs
int pairs = 0;
for(Integer frequency : colors.values()) {
pairs += frequency >> 1;
}
System.out.println(pairs);
}
}
This isn't a good solution. If the input is suppose [1000,1005,1000,1002]. Will you create an array of 1005 ?
ReplyDeleteyou will have to implement a hash table then.
DeleteA better approach
Deleteint sockMerchant(int n, vector ar) {
int total_pair = 0 ;
int i = 0 , j = 0 ;
int sock_count = 0 ;
vector sock;
sort(ar.begin(), ar.end());
while(i < ar.size()-1){
sock_count = 1;
for( j = i + 1 ; j < ar.size() ; j++){
if(ar[i] == ar[j]){
sock_count++;
}
else{
i = j;
break;
}
}
sock.push_back(sock_count);
if(i != j){
i = j;
}
cout<<i<<endl;
}
for(int i = 0 ; i < sock.size() ; i ++){
total_pair+=(sock[i]/2);
}
return total_pair;
}
try with this one no need to use two arrays ...
Deleteimport java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the sockMerchant function below.
static int sockMerchant(int n, int[] ar) {
int i;
int count=0;
int[] vr = new int[n];
int visited=-1;
int pairs = 0;
for(i=0;i<n;i++)
{
for(int j=i+1;j<n-1;j++)
{
if(ar[i]!=visited && ar[j]!=visited)
{
if(ar[i]==ar[j])
{
count=count+1;
ar[i]=visited;
ar[j]=visited;
}
}
}
}
return(count);
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
int[] ar = new int[n];
String[] arItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < n; i++) {
int arItem = Integer.parseInt(arItems[i]);
ar[i] = arItem;
}
int result = sockMerchant(n, ar);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
Sir can explain the role of visited in this code
Deleteim pretty sure, its becuase when comparing and counting the socks, we dont want a repetition in the same sock! for example if its 20 20 20 30 50 20, it needs to only count 20 4 times! if we dont keep a variable that counts the numbers we visited, it'll count 20 in seperate occasions like 20=4, 20=3,20=2! atleast that was the issue i encountered while coding!
Deletewhy did yoou do a right shift to pairs? is it some hack?
ReplyDeletehaha
Deletefunction sockMerchant($n, $ar) {
ReplyDelete$socks = [];
//get count of each colors
for ($i = 0; $i < $n; $i++ ) {
$color = $ar[$i];
if (isset($socks[$color])) {
$socks[$color] = $socks[$color] + 1;
} else {
$socks[$color] = 1;
}
}
//find out pairs of colors
$totalPairs = 0;
foreach ($socks as $sock) {
$totalPairs = $totalPairs + floor(($sock / 2));
}
return $totalPairs;
}
$colors = [10, 20, 20, 10, 10, 30, 50, 10, 20];
echo sockMerchant(9, $colors);
Can You Please tell me why you use right shift to find pairs in HashMap
ReplyDeleteI think it's just a division by 2 without a remainder. Because we counted every single sock so we need to divide by 2 to get the number of pairs
ReplyDeleteint counter=0;
ReplyDeleteint count=0;
for(int i=0;i<ar.length;i++)
{
count=1;
for(int j=i+1;j<ar.length;j++)
{
if(ar[i]==ar[j])
{
count++;
}
}
if(count==2)
{
counter++;
}
}
return counter;
if (count % 2 == 0)
Delete{
counter++;
}
so the j=i+1 loop counts the number of socks, suppose its 6. counter would count only once rite?
Delete
ReplyDeleteJohn works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
For example, there are socks with colors . There is one pair of color and one of color . There are three odd socks left, one of each color. The number of pairs is .
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the sockMerchant function below.
static int sockMerchant(int n, int[] ar) {
int counter=0;
int count=0;
for(int i=0;i<ar.length;i++)
{
count=1;
for(int j=i+1;j<ar.length;j++)
{
if(ar[i]==ar[j])
{
count++;
}
}
if(count%2==0)
{
counter++;
}
}
return counter;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
int[] ar = new int[n];
String[] arItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < n; i++) {
int arItem = Integer.parseInt(arItems[i]);
ar[i] = arItem;
}
int result = sockMerchant(n, ar);
System.out.println("Number of pair of socks"+result);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedWriter.close();
scanner.close();
}
}
wow...this is so easy and clear. Thank you!!!
DeleteAny even number divided by 2 will give remainder 0.So, Can u please explain what is actually checked in if(count%2==0) .I didn't understand what is it's purpose
Deletestatic int sockMerchant(int n, int[] ar) {
ReplyDeleteint pair=0;
for (int i = 0; i < n; i++) {
int count=0;
for (int j = i + 1; j < n; j++){
if (ar[i] == ar[j] && ar[i]>=0) {
count++;
ar[j]=-1;
}
else continue;
if((count+1)%2==0 && count>0)
pair++;
}
count++;
}
return pair;
}
for python
ReplyDeletedef sockMerchant(n, ar):
result = 0
ar.sort()
i = 0
j = 1
while i < len(ar):
if(ar[i] == ar[j]):
result=result+1
i=i+1
j=j+1
i=i+1
j=j+1
if(j == len(ar)):
break
return result
Python 3:
ReplyDeletedef sockMerchant(n, ar):
x=[]
y=[]
ar.sort()
while len(ar)>1:
if ar[0]==ar[1]:
x.append(ar[:2])
del ar[:2]
else:
del ar[0]
return len(x)
That's very good
DeleteCould you please let me know the reason to sort the array?
Deletestatic int sockMerchant(int n, int[] ar)
ReplyDelete{
Arrays.sort(ar);
int count=0;
int sum=0;
for(int i=0;i<n-1;i++)
{
if(ar[i]==ar[i+1])
{
count++;
}
if(ar[i]!=ar[i+1])
{
if(count%2==1)
{
sum=sum+count+1;
}
else
{
sum=sum+count;
}
count=0;
}
}
if(count%2==1)
{
sum=sum+count+1;
}
else
{
sum=sum+count;
}
sum=sum/2;
return sum;
}
Is there any source which explains codes line to line clearly?
ReplyDelete//javascript solution
ReplyDeletefunction sockMerchant(n, arr) {
var counter=0;
var count=0;
for(var i=0;i<arr.length;i++)
{
count=1;
for(var j=i+1;j<arr.length;j++)
{
if(arr[i]==arr[j])
{
count++;
}
}
if (count % 2 == 0)
{
counter++;
}
}
return counter;
}
Tnqsm
Deleteconst n = 9;
ReplyDeletelet ar = [10, 20, 20, 10, 10, 30, 50, 10, 20];
function sortAndCount(n, ar) {
let sorted = ar.sort((a,b) => a - b);
let pair = 0;
for(let i = 0; i < n-1; i++ ) {
console.log(i)
if(sorted[i] === sorted[i + 1]) {
pair ++;
i += 1;
}
}
return pair;
}
console.log(sortAndCount(n, ar))
#include
ReplyDeleteusing namespace std;
vector split_string(string);
// Complete the sockMerchant function below.
int sockMerchant(int n, vector ar) {
int i, pairs = 0;
if(n >= 1 && n <= 100){
sort(ar.begin(), ar.end());
for(i = 0; i < n; i++){
if(ar[i] == ar[i+1]){
pairs = pairs + 1;
i = i + 1;
}
}
}
return pairs;
}
def sockMerchant(n, ar):
ReplyDeletepair=0
for i in range(n):
for j in range(i+1,n):
if ar[i]==ar[j]:
if ar[i]==ar[j]=="done already":
continue
ar[j]="done already"
pair+=1
break
return pair
int sockMerchant(int n, vector ar) {
ReplyDeleteset s(ar.begin(),ar.end());
vector v(s.begin(),s.end());
int ss=(int)v.size();
int counter=0;
int count=0;
int b=(int)ar.size();
for(int i=0;i<ss;i++){
if(v[i]==ar[i])
count=1;
cout<<"....\n";
for(int j=i+1;j<b;j++){
if(v[i]==ar[j]){
count++;
cout<<count<<" \n";
}
}
counter= counter+int(count/2);
count=0;
cout<<"----"<<counter<<"\n";
}
return counter;
}
n=int(input())
ReplyDeletelist1=[]
list2=[]
for i in range(n):
a=int(input())
list1.append(a)
list2.append(0)
counter=0
for i in range(len(list1)):
element=list1[i]
for j in range(i+1,len(list1)):
if element==list1[j] and list2[j]==0 and list2[i]==0:
counter+=1
list2[j]=1
list2[i]=1
print(list2)
break
print(counter)
py3 code .def sockMerchant (n, number):
ReplyDeletetotal = 0
for i in range(n-1):
sorted(number)
total= i//2
return total
n = int(input())
number = list(map(int, input().split()))
print(sockMerchant(n, number))
def sockMerchant (n, number):
ReplyDeletetotal = 0
for i in range(n-1):
sorted(number)
total= i//2
return total
n = int(input())
number = list(map(int, input().split()))
print(sockMerchant(n, number))
from itertools import groupby
ReplyDeleten = int(raw_input())
c = map(int, raw_input().split())
ans = 0
for i in [len(list(group)) for key, group in groupby(sorted(c))]:
ans = ans + i/2
print ans
#include
ReplyDelete#include
using namespace std;
int sockMerchant(int n,int *ar)
{
int count=0;
int freq[101]={};
for(int i=0;i<n;i++)
{
freq[ar[i]]++;
}
for(int j=0;j<101;j++)
{
if(freq[j]%2!=0)
count++;
}
return count;
}
int main()
{
int ar[]={10,20,20,30,10,30,50,10,20,10};
int n=sizeof(ar)/sizeof(ar[0]);
cout<<sockMerchant(n,ar);
return 0;
}
//Very Basic Javascript Solution
ReplyDeletefunction sockMerchant(n, ar) {
var pair = 1;
for (var i = 0; i < n; i++) {
for (var j = i + 1; j < n; j++) {
if (ar[i] == ar[j]) {
pair += 1;
ar[j] = 0;
}
break;
}
}
return pair
}
c#:
ReplyDeletestatic int sockMerchant(int n, int[] ar) {
int count=0,j=0,pair=0;
Array.Sort(ar);
for(int i=0;i0)
{
count++;
pair=pair+(count/2);
}
}
else
{
count++;
pair=pair+(count/2);
count=0;
}
}
return pair;
}
static int sockMerchant(int n, int[] ar) {
Deleteint count=0,j=0,pair=0;
Array.Sort(ar);
for(int i=0;i0)
{
count++;
pair=pair+(count/2);
}
}
else
{
count++;
pair=pair+(count/2);
count=0;
}
}
return pair;
}
static int sockMerchant(int n, int[] ar) {
ReplyDeleteint count=0,j=0,pair=0;
Array.Sort(ar);
for(int i=0 ;i< n - 1 ; i++)
{
j=i+1;
if(ar[i]==ar[j])
{
count++;
if(j==n-1&&count>0)
{
count++;
pair=pair+(count/2);
}
}
else
{
count++;
pair=pair+(count/2);
count=0;
}
}
return pair;
}
Can someone plz provide the answer in Golang?
ReplyDeleteC# solution:
ReplyDeletepublic static int sockMerchant(int n, List ar)
{
int count=0;
int counter=0;
for(int i=0;i<n-1;i++)
{
count=1;
for(int j=i+1;j<n;j++)
{
if(ar[i]==ar[j])
{
count++;
}
}
if(count%2==0)
{
counter++;
}
}
return counter;
}
public static int sockMerchant(int n, List ar) {
ReplyDeleteMap map = new HashMap<>();
for (int i = 0; i < n; i++) {
if(map.containsKey(ar.get(i))){
map.put(ar.get(i), map.get(ar.get(i))+1);
}else {
map.put(ar.get(i), 1);
}
}
//divide value of each key by 2
int no_of_pairs = 0;
Iterator> itr = map.entrySet().iterator();
while (itr.hasNext()){
Map.Entry entry = itr.next();
no_of_pairs = no_of_pairs + (entry.getValue() / 2);
}
//return (ar.size()- (no_of_pairs*2));
return no_of_pairs;
}
//PROPER WAY TO DO THIS PROBLEM!
ReplyDeleteint sockMerchant(int n, vector ar) {
sort(ar.begin(),ar.end());
int count=0;
for(int i=0;i<ar.size();i++)
{
for(int j=i+1;j<ar.size();j++)
{
if(ar.at(i)==ar.at(j))
{
// cout<<ar.at(i)<<" and "<<ar.at(j)<<" | "; for refrence
count++;
i+=1;
break;
}
}
}
return count;
}
For Complete explanation of C++ please visit - SchoolingAxis
ReplyDeleteAnother approach but complexity is high:
ReplyDeletedef sockMerchant(n, ar):
# Write your code here
c=0
for i in range(0,n-1):
while ar[i]==0:
i+=1
for j in range(i+1,n):
while ar[j]==0:
j+=1
if ar[i]==ar[j]:
c+=1
ar[i]=0
ar[j]=0
break
return c
I came with this solution in Python, I created a dictionary from array, it takes only unique colors and counts how many of them in the array, then I put the numbers of different colors into the list and loop thru, checking their division by 2 and add result to total.
ReplyDeletedef sockMerchant(n, ar):
count= 0
#create a dictionary with unique color values and count them
colours_count=(dict((i, ar.count(i)) for i in ar))
#create a list of counted colours
list1 = colours_count.values()
#loop thru the list
for x in list1:
if x>1:
#only values which greater that 1 can be counted
y=math.floor(x/2)
count+=y
return count
import java.io.*;
ReplyDeleteimport 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 ar) {
// Write your code here
int count=0;
Mapmap=new HashMap<>();
for(Integer i:ar)
{
Integer j=map.get(i);
map.put(i, (j==null)?1:j+1);
}
for(Map.Entryval:map.entrySet())
{
if(val.getValue()>1)
{
count=count+val.getValue()/2;
}
}
return count;
}
}
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 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();
}
}
You're definitely familiar with the best coding language C++ that developers use to develop their projects and they get all their queries like "c++ change console color" answered properly. Developers are finding an appropriate answer about c++ change console color related to the C++ coding language.
ReplyDelete