Issue
I am trying to solve the problem of determining how many pairs of occurrences in the array ar there are for each integer in the array:
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) {
// Write your code here
for(int i = 0; i<n ; i++) {
int occurrences[];
occurrences[i] = Collections.frequency(ar, ar[i]);
}
int pairs = 0;
for(int j = 0; j<n; j++) {
pairs = pairs + (0.5*occurrences[j]) ;
}
return pairs;
}
}
I keep getting the following two errors and after reviewing the Java API and various online resources cannot determine the issue. Can someone advise?
Solution.java:31: error: array required, but List<Integer> found
occurrences[i] = Collections.frequency(ar, ar[i]);
^
Solution.java:39: error: cannot find symbol
pairs = pairs + (0.5*occurrences[j]) ;
^
symbol: variable occurrences
location: class Result
2 errors
Solution
Great idea to google "Java access list element"
public static int sockMerchant(int n, List<Integer> ar) {
// Write your code here
int occurrences[];
int pairs = 0;
Set<Integer> distinct = new HashSet<>(ar);
for (Integer s: distinct) {
pairs += 0.5*Collections.frequency(ar, s);
}
/*for(int j = 0; j<n; j++) {
pairs = pairs + (0.5*occurrences[j]) ;
}*/
return pairs;
}
}
Answered By - don