So, I wanted to have the count for number of pairs of same integer there are in an array for which I used a HashMap
Input contains two lines:
Integer n:
Signifies the size of input
Input numbers separated by white space character:
E.g 4 6 6 7 7 8 7 6 4
For the same input,
Expected Output:
3
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class SockMerchant {
public int[] returnsockArr() {
Scanner sc = new Scanner(System.in);
int arraySize = sc.nextInt();
int[] sockArr = new int[arraySize];
for(int i = 0;i <= arraySize-1; i++) {
sockArr[i] = sc.nextInt();
}
sc.close();
return sockArr;
}
public int returnCount(Map<String, Object> mapCount) {
int count = 0;
for(String keyName : mapCount.keySet()) {
int value = (int)mapCount.get(keyName);
count = count+(value/2);
}
return count;
}
public int setMapAndReturnCount(int[] sockArr) {
Map<String, Object> mapCount = new HashMap<String, Object>();
for(int j = 0;j<= sockArr.length-1;j++) {
if(mapCount.containsKey(Integer.toString(sockArr[j]))) {
mapCount.put(Integer.toString(sockArr[j]), (int)mapCount.get(Integer.toString(sockArr[j]))+1);
}
else {
mapCount.put(Integer.toString(sockArr[j]), 1);
}
}
return returnCount(mapCount);
}
public static void main(String args[]) {
SockMerchant sm = new SockMerchant();
int[] sockArr = sm.returnsockArr();
int finalCount = sm.setMapAndReturnCount(sockArr);
System.out.println(finalCount);
}
}
I think that I have complicated the solution a bit too much
Is there a better approach to do the same thing?