-1

I'm using ConnectivityInspector to get the connected trees from a graph using the method connectedSets() which give me a List of Hashsets

ConnectivityInspector s = new ConnectivityInspector<>(graph);
            System.out.println(s.connectedSets());

it would give me all the trees of the forest for example [ [13, 14], [15], [16, 17, 18, 19, 20, 21, 22], [23], [36], [38, 39], [40], [41], [52], [56, 120], [58, 122, 186] ]

My question now that I stuck on it is that how to get the sum of every tree to get then the average of this tree. for example: s.connectedSets().get(0) = [13, 14]. How can I add both 13 and 14 and before that make them integer . I try many ways but I couldn't catch the solution .

zain
  • 1

1 Answers1

0

First, I recommend going into more detail..i.e. code snippets, a more thorough explanation of what you are attempting to do, etc.

Second, from what I am understanding, you have an instance of ConnectivityInspector and you want to get the sum of every tree, then find the average of the tree. Looking at the documentation, we can see that connectedSets() return a type List<Set<V>>. Now, I am assuming that your V=int or Integer You can use a Stream in the nifty Java 8 to sum each set in the list, then store each sum in a List. The value at index i in the list, sums, is the sum of the tree at index i in the connSets. We can then use sum again to find the sum of our list of sums, then divide that by the number of elements in all of the list of sets.

public int calculateAverage(List<Set<Integer>> connSets) {

    List<Integer> sums = new ArrayList<Integer>();
    int elementCount = 0;

    for(int i = 0; i < connSets.size(); i++) {
        elementCount += connSets.get(i).size();
        sums.add(i, connSets.get(i).stream().mapToInt(Integer::intValue).sum());
    }

    return sums.stream().mapToInt(Integer::intValue).sum()/elementCount;
}