How to create a list corresponding to each number from 2 to 100 that will contain numbers from an array that are its multiples?

Shivani_Saha :

Recently i came across this question and could not figure out an optimal solution for it.

Suppose we have an array of numbers of any range like 9,-3,0,4,11,2,-8,..... We need to print numbers from 2 to 100 and corresponding to each of them we need to print a list of numbers from the array such that the number in the array is divisible by it. Example: Using the existing array in example, 2 -> 4,2,-8,... 3 -> -3,9,... 4 -> 4,-8,... and like this upto 100.

I tried working out the solution by dividing each number of the array by numbers from 2 to 100 and subsequently creating the list corresponding to each of them. But that didn't seem to me an optimal solution.

I even tried grouping numbers like a number which is divisible by 8 will be divisible by 2 and 4 so we don't need to divide it again. This would reduce some operations and complexity but would in turn, require creating such groups.

Please can anyone help finding an optimal solution for this problem by reducing the need to divide each number by 2 to 100.

Eritrean :

To solve the given problem I would choose one of the two following approaches:

Version 1

Two simple nested loops in combination with the method map.computeIfAbsent

int[] myArray = {3,5,1,-7,6,34,88,2,-8,9,10,4,33};
Map<Integer,List<Integer>> version1 = new HashMap<>();
for(int i = 2; i< 100; i++){
    for(int x : myArray){
        if(x%i==0)
           version1.computeIfAbsent(i, k -> new ArrayList<>()).add(x);
    }            
}
System.out.println(version1);

Version 2

A solution only with stream operations

    Map<Integer,List<Integer>> version2 = Arrays.stream(myArray).distinct().boxed()
            .flatMap(p -> IntStream.range(2, 100).filter(i -> p%i ==0).boxed()
                    .map(l->new AbstractMap.SimpleEntry<>(l,p)))
            .collect(Collectors.groupingBy(Map.Entry::getKey,
                    Collectors.mapping(Map.Entry::getValue, Collectors.toList())));

    System.out.println(version2);

There are certainly more elegant solutions or solutions that are optimal in terms of complexity. But I think the approaches here are short and easy to read.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326545&siteId=1