Sock Merchant Hacker rank solution in c
John works at a clothing store. He has a large pile of socks that he must pair them by color for sale.
You will be given an array of integers representing the color of each sock. Determine how many pairs of socks with matching colors there are.
John works at a clothing store and he's going through a pile of socks to find the number of matching pairs.
More specifically, he has a pile of loose socks where each sock is labeled with an integer, n, denoting its color. He wants to sell as many socks as possible, but his customers will only buy them in matching
pairs. Two socks, and , are a single matching pair if they have the same color ( Ci==Cj).
Given and the color of each sock, how many pairs of socks can John sell?
Solution to sock merchant problem in just 2 STEPS:
Step 1:-
Rearrange the given order in ascending order.
for(i=0;i<n;i++){
for(j=i+1;j<n;j++)
{
if(arr[i]>arr[j]){
a=arr[i];
arr[i]=arr[j];
arr[j]=a;
}
}
Given order is :
EX- 10 20 20 10 10 30 50 10 20
After rearranging in ascending order:
10 10 10 10 20 20 20 30 50
Step 2:-
Now compare first element to it's next element if it matches then it's a pair.
for(i=0;i<n;i++){ for(j=i+1;j<n;j++){ if(arr[i]==arr[j]){ count++; i++; break; } } }
If you are beginner then I will advice to remove all data after header files and put your own code. It becomes easy to code then.
#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
int a,n,i,j,count=0;
scanf("%d",&n);
int arr[n];
for(i=0;i<n;i++){
scanf("%d",&arr[i]);
}
for(i=0;i<n;i++){
for(j=i+1;j<n;j++)
{
if(arr[i]>arr[j]){
a=arr[i];
arr[i]=arr[j];
arr[j]=a;
}
}
}for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(arr[i]==arr[j]){
count++;
i++;
break;
}
}
}
printf("%d",count);
return 0;
}
Comments
Post a Comment