HackerRank Problem #2
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
Get riaevnt’s stories in your inbox
Join Medium for free to get updates from this writer.
The first line contains an integer n, the number of socks represented in ar.
The second line contains n space-separated integers, ar[i], the colors of the socks in the pile.
Constraints
- 1 ≤ n ≤ 100
- 1 ≤ ar[i] ≤ 100 where 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
3Explanation
There are three pairs of socks.
Solutions
import java.io.*;
import java.util.*;
import java.util.stream.*;
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 result=0;
// Write your code here
//1. Do sorting array
Integer[] temp = new Integer[n];
for(int i=0; i<n-1; i++){
for(int j=0; j<n-1; j++){
if(ar.get(j)<ar.get(j+1)){
temp[j] = ar.get(j);
ar.set(j, ar.get(j+1));
ar.set(j+1, temp[j]);
}
}
}
//Debugging
System.out.println("in loop: "+ar.toString());
//Counting pairs of array
for(int i=0; i<n-1;){
if(ar.get(i)==ar.get(i+1)){
//If get a pair of array, then skip one index array, jump from i to i+2
result = result +1;
i = i+2;
} else {
//If didn't get a pair of array, then move to the next array or jump from i to i+1
i = i+1;
}
}
return result;
}
}
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();
}
}






