I came across a problem where given a array of integer arrays of different lengths [[1,2,3],[4,1,1], [9,2,1]]
you need to return an array of arrays, each array containing indices of the arrays (of the input array) such that the corresponding arrays have the same mean: [[0,1],[2]]
This seems relatively simple to solve using Python:
def groupByMean(a):
d,e=[],[]
for i,j in enumerate(a):
if sum(j)/len(j)not in e:
e+=[sum(j)/len(j)]
d+=[[i]]
else:
d[e.index(sum(j)/len(j))]+=[i]
return d
However, when trying to solve this in Java this was my approach: using a hashmap, map each new mean to a list of the corresponding indices. Then iterate the hashmap, to get the arraylists and convert them to int[] arrays and construct the 2d array ...
Is there a simpler approach to solve this using Java?
This is my java code - looking for a different way to solve this:
public static void main(String[] args) {
int[][] arr = { { 1, 2, 3 }, { 2, 3, 4 }, { 2, 4, 0 } };
for (int[] nums : groupBySum(arr)) {
for (int n : nums) {
System.out.print(n + " ");
}
System.out.println();
}
}
public static int[][] groupByMean(int[][] arr) {
Map<Double, List<Integer>> map = new HashMap<>();
int i = 0;
for (int[] nums : arr) {
double average = getAverage(nums);
if (!map.containsKey(average)) {
List<Integer> indices = new ArrayList<>();
indices.add(i);
map.put(average, indices);
} else {
map.get(average).add(i);
}
i++;
}
int[][] result = new int[map.size()][];
int row = 0;
for (List<Integer> indices : map.values()) {
result[row] = new int[indices.size()];
for (int k = 0; k < indices.size(); k++) {
result[row][k] = indices.get(k);
}
row++;
}
return result;
}
public static double getAverage(int[] arr) {
int sum = 0;
for (int num : arr) {
sum += num;
}
return ((double) sum) / arr.length;
}