#478 Parallel Sum of a List
A list of numbers is provided, and the sum of all numbers must be calculated.
The calculation must be fast. Because the list is large, the sum should be calculated as follows:
split the input list into parts using the split method
(no time needs to be spent implementing it; it is included only to avoid adding a library).
Each sublist must be submitted to a separate thread where its sum is calculated, using 10 threads in total. After all 10 threads finish, collect and add the results to obtain the final sum.
/**
* Calculate the sum of list elements, more than 1 million elements,
* using 10 threads.
*/
public static long sum(List<Long> numbers) {
final int threads = 10;
List<List<Long>> subLists = split(numbers, threads);
// TODO: make it work!
return ???;
}
private static List<List<Long>> split(List<Long> numbers, int parts) {
int size = numbers.size();
int subListSize = (int) Math.ceil((double) size / parts);
List<List<Long>> result = new ArrayList<>(parts);
for (int i = 0; i < parts; i++) {
int fromIndex = i * subListSize;
if (fromIndex >= size) {
result.add(Collections.emptyList());
} else {
int toIndex = Math.min((i + 1) * subListSize, size);
List<Long> sublist = numbers.subList(fromIndex, toIndex);
result.add(sublist);
}
}
return result;
}
Question review
Sign in to start the dialogue
The mentor keeps the context of the current question and your previous messages.
Sign in
Available with Premium
This is just one of the solutions available with Premium. And more:
- 250+ advanced lectures
- 1300+ practice exercises
- 500+ solutions to problems from real interviews
- Personalized Java Hub certificates
- Expanded access to the AI mentor