Question

In: Computer Science

You are given an array of arrays a. Your task is to group the arrays a[i]...

You are given an array of arrays a. Your task is to group the arrays a[i] by their mean values, so that arrays with equal mean values are in the same group, and arrays with different mean values are in different groups.

Each group should contain a set of indices (i, j, etc), such that the corresponding arrays (a[i], a[j], etc) all have the same mean. Return the set of groups as an array of arrays, where the indices within each group are sorted in ascending order, and the groups are sorted in ascending order of their minimum element.

Example

  • For
  • a = [[3, 3, 4, 2],
  •      [4, 4],
  •      [4, 0, 3, 3],
  •      [2, 3],
  •      [3, 3, 3]]

the output should be

meanGroups(a) = [[0, 4],

                 [1],

                 [2, 3]]

  • mean(a[0]) = (3 + 3 + 4 + 2) / 4 = 3;
  • mean(a[1]) = (4 + 4) / 2 = 4;
  • mean(a[2]) = (4 + 0 + 3 + 3) / 4 = 2.5;
  • mean(a[3]) = (2 + 3) / 2 = 2.5;
  • mean(a[4]) = (3 + 3 + 3) / 3 = 3.

There are three groups of means: those with mean 2.5, 3, and 4. And they form the following groups:

  • Arrays with indices 0and 4 form a group with mean 3;
  • Array with index 1 forms a group with mean 4;
  • Arrays with indices 2and 3 form a group with mean 2.5.

Note that neither

meanGroups(a) = [[0, 4],

                 [2, 3],

                 [1]]

nor

meanGroups(a) = [[0, 4],

                 [1],

                 [3, 2]]

will be considered as a correct answer:

    • In the first case, the minimal element in the array at index 2 is 1, and it is less then the minimal element in the array at index 1, which is 2.
    • In the second case, the array at index 2 is not sorted in ascending order.
  • For
  • a = [[-5, 2, 3],
  •      [0, 0],
  •      [0],
  •      [-100, 100]]

the output should be

meanGroups(a) = [[0, 1, 2, 3]]

The mean values of all of the arrays are 0, so all of them are in the same group.

Input/Output

  • [execution time limit] 3 seconds (java)
  • [input] array.array.integer a

An array of arrays of integers.

Guaranteed constraints:
1 ≤ a.length ≤ 100,
1 ≤ a[i].length ≤ 100,
-100 ≤ a[i][j] ≤ 100.

  • [output] array.array.integer

An array of arrays, representing the groups of indices

Solutions

Expert Solution

Code:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class Mean {
  
   static public void main(String args[])
   {
       // Initializing variables
       int[][] a = new int[100][100]; // Array of arrays for holding the inputs
       Map<Integer,ArrayList<Integer>> averagemaps = new HashMap<Integer,ArrayList<Integer>>(); // Map to contain the average and the list of array indexes
       List<Integer> averages = new ArrayList<Integer>(); // List of averages of the arrays
       Scanner sc = new Scanner(System.in);
      
       // Input for the array of arrays
       System.out.println("Enter the number of arrays: ");
       int noArrays = sc.nextInt();
      
       for(int i = 0; i < noArrays; i++)
       {
           System.out.println("Enter the number of elements in the array "+i+":");
           int noElements = sc.nextInt();
           int sum = 0;
           int avg = 0;
           System.out.println("Enter the elements of the array "+i+" one by one:");
           for(int j = 0; j < noElements; j++)
           {
               a[i][j] = sc.nextInt(); // Input for each elements in the array.
               sum += a[i][j];   // Calculating the sum of the elements in the array.
           }
          
           avg = sum/noElements; // calculating average for the array
          
           // checking if the average is inside the list or not
           if(!averages.contains(avg))
           {  
               // If the average is not already in the list
               // Adding the average into the list
               averages.add(avg);
               // create an array list to
               // hold the list of indices which has the same array
               ArrayList<Integer> a1 = new ArrayList<Integer>();
               a1.add(i);
               // Mapping the average to the list of indices.
               averagemaps.put(avg, a1);
           }
           else
           {
               // The average is present in the list
               // Adding the index to the array list
               // mapped to it.
               averagemaps.get(avg).add(i);
           }
       }
      
       // Sorting the index arrays for each average
       // in ascending order
       Iterator itr=averages.iterator();
       int index = 0;
       while(itr.hasNext()){
              Collections.sort(averagemaps.get(itr.next()));
       }
      
       // For sorting the array of indices based on their lowest number
       // Since the arrays are in a map, the map needs to be sorted.
       // There is no function to sort the map, Hence the map is converted to
       // a list of entersets.
        List<Map.Entry<Integer,ArrayList<Integer>>> list =
                new LinkedList<Map.Entry<Integer,ArrayList<Integer>>>(averagemaps.entrySet());

        // Using the sort function to sort the list. The list should be sorted based on the minimum
        // element in each array.
        Collections.sort(list, new Comparator<Map.Entry<Integer,ArrayList<Integer>>>() {
            public int compare(Map.Entry<Integer,ArrayList<Integer>> o1,
                               Map.Entry<Integer,ArrayList<Integer>> o2) {
               // since the elements in the arrays are already sorted
               // the element in the index 0 will be the smallest element
                return (o1.getValue().get(0)).compareTo(o2.getValue().get(0));
            }
        });

        // Converting the list back to a hashmap
        averagemaps = new HashMap<Integer,ArrayList<Integer>>();
        for (Map.Entry<Integer,ArrayList<Integer>> entry : list) {
           averagemaps.put(entry.getKey(), entry.getValue());
        }
      
        // Initializing an array of array for the output
        // The outer array dimension is defined.
        // The inner array dimension can be defined based on the
        // size of the indices array
       int[][] answer = new int[averages.size()][];
      
       itr = averages.iterator();
      
       // Iterate through the averages lists
       while(itr.hasNext())
       {
           ArrayList<Integer> i = averagemaps.get(itr.next());
           Iterator iterr=i.iterator();
           answer[index] = new int[i.size()];
           int innerindex = 0;
           while(iterr.hasNext())
               answer[index][innerindex++] = (Integer)iterr.next(); // adding the array of indices into the output array.
           index++;
       }
      
       // Printing the arrays of arrays.
       System.out.print("[ ");
       for(int i = 0; i < answer.length; i++)
       {
           System.out.print("[ ");
           for(int j = 0;j < answer[i].length; j++)
               System.out.print(answer[i][j]+ ", ");
           System.out.println("]");
       }
       System.out.println("]");
   }
}

Output:

Enter the number of arrays:
4
Enter the number of elements in the array 0:
3
Enter the elements of the array 0 one by one:
-5
2
3
Enter the number of elements in the array 1:
2
Enter the elements of the array 1 one by one:
0
0
Enter the number of elements in the array 2:
1
Enter the elements of the array 2 one by one:
0
Enter the number of elements in the array 3:
2
Enter the elements of the array 3 one by one:
-100
100
[ [ 0, 1, 2, 3, ]
]


Related Solutions

. As input you are given two arrays: an array of numbers ? and an array...
. As input you are given two arrays: an array of numbers ? and an array ? of queries where each query is a target number. The array ? is unsorted and may contain duplicates. Your goal is, for each query ? in the array ?, count the number of pairs in the array ? that sums up to ?; that is, the number of distinct pairs of indices [?, ?], with ? < ?, such that ?[?] + ?[?]...
Using Java please You are given an array of integers arr. Your task is to count...
Using Java please You are given an array of integers arr. Your task is to count the number of contiguous subarrays, such that each element of the subarray appears at least twice. E.g For arr = [0, 0, 0], the output should be duplicatesOnSegment(arr) = 3.
Given an array of positive integers a, your task is to calculate the sum of every...
Given an array of positive integers a, your task is to calculate the sum of every possible a[i] ∘a[j], where a[i]∘a[j] is the concatenation of the string representations of a[i] and a[j] respectively. Example For a = [10, 2], the output should be concatenationsSum(a) = 1344. a[0] ∘a[0] = 10 ∘10 = 1010, a[0] ∘a[1] = 10 ∘2 = 102, a[1] ∘a[0] = 2 ∘10 = 210, a[1] ∘a[1] = 2 ∘2 = 22. So the sum is equal to...
Problem 1: Unsorted arrays Given an array of integers that is unsorted, implement the following functions:...
Problem 1: Unsorted arrays Given an array of integers that is unsorted, implement the following functions: • myAdd ( ): add an integer d to the array; return 0 if the operation is successful; return a negative number otherwise. • search ( ): given an integer d, if d is found in the array, return the index of the cell containing d. Return a negative number otherwise (e.g., d is not found in the array). • myRemove ( ): Step...
You have been given a solution that contains a Group I, a Group II, and a...
You have been given a solution that contains a Group I, a Group II, and a Group III cation. · Develop a qualitative analysis scheme for these cations by selecting reagents and conditions for reactions. · Write the balanced net reaction for each cation reaction.
Your task is to modify the program from the Java Arrays programming assignment to use text...
Your task is to modify the program from the Java Arrays programming assignment to use text files for input and output. I suggest you save acopy of the original before modifying the software. Your modified program should: contain a for loop to read the five test score into the array from a text data file. You will need to create and save a data file for the program to use. It should have one test score on each line of...
Overlapping Arrays (C++) An array overlaps another array if all elements of the latter array exist...
Overlapping Arrays (C++) An array overlaps another array if all elements of the latter array exist in the former array. They need not necessarily be in the same order. For example, [1,7,3,4,2] overlaps [1,2,3] because 1,2 and 3 exist in [1,7,3,4,2]. To make the implementation easy, [1,7,3,4,2] overlaps [1,1,2,3] as well. We don’t need to check whether 1 appears twice in the first array. Write a program that lets the user enter two arrays and displays whether the first array...
For your job as the business reporter for a local newspaper, you are given the task...
For your job as the business reporter for a local newspaper, you are given the task of putting together a series of articles that explains the power of the time value of money to your readers. Your editor would like you to address several specific questions in addition to demonstrating for the readership the use of the time value of money techniques by applying them to several problems. What should be your response to the following memorandum from your editor?...
For your job as the business reporter for a local​ newspaper, you are given the task...
For your job as the business reporter for a local​ newspaper, you are given the task of putting together a series of articles that explain the power of the time value of money to your readers. Your editor would like you to address several specific questions in addition to demonstrating for the readership the use of time value of money techniques by applying them to several problems. What would be your response to the following memorandum from your​ editor? ​To:...
In c++ Array expander Write a function that accepts an int array and the arrays size...
In c++ Array expander Write a function that accepts an int array and the arrays size as arguments. The function should create a new array that is twice the size of the argument array. The function should create a new array that is twice the size of the argument array. The function should copy the contents of the argument array to the new array and initialize the unused elements of the second array with 0. The function should return a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT