I found this challenge to be interesting so I gave it a try. I wrote it in Java but it can easily be converted to any language you want.
int[][] arr = { { 3, 3, 4, 2 }, { 4, 4 }, { 4, 0, 3, 5 }, { 3, 3 } };
Map<Integer, List<Integer>> map = new TreeMap<>();
for (int i = 0; i < arr.length; i++) {
int mean = mean(arr[i]);
if (map.containsKey(mean)) {
List<Integer> l = map.get(mean);
l.add(i);
map.put(mean, l);
} else {
List<Integer> l = new ArrayList<>();
l.add(i);
map.put(mean, l);
}
}
Choose TreeMap as it keeps the keys in ascending order (sorted). And this Map will hold means as keys and indices as values in a List. Then we iterate over the array, find mean, add it to the map and index in a list to the map, and if map already contains the mean, then add the index to the existing list.
int finArr[][] = new int[map.values().size()][]; //this will hold the final answer--arrays of indices.
List<Integer> keys = new ArrayList<>(map.keySet());
map.keySet() would return keys in ascending order (because we chose to create a Map of type TreeMap above), but we want to instantly convert it to ArrayList because we cannot pull values from a Set using index. And we also need index to feed arrays at correct locations into the final array.
for (int i = 0; i < keys.size(); i++) {
finArr[i] = map.remove(keys.get(i)).stream().mapToInt(val -> val).toArray();
}
In above for loop, we are basically pulling values (which is a List) out of map, and converting that List to primitive int array.
System.out.print("[ ");
for (int[] is : finArr) {
System.out.print(Arrays.toString(is) + " ");
}
System.out.println("]");
output: [ [0, 2, 3], [1] ]
The mean meathod:
private static int mean(int[] arr) {
int sum = 0;
for (int i : arr) {
sum += i;
}
return sum / arr.length;
}
Bonus::
This variation of InsertionSort can sort the array based on mean values.
for (int i = 1; i < arr.length; i++) {
int[] kk = arr[i];
int key = mean(arr[i]);
int j = i - 1;
while (j > -1 && mean(arr[j]) > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = kk;
}
for (int[] is : arr) {
System.out.println(Arrays.toString(is));
}
output: [3,3,3,4]