← 返回 google 的题目列表Design and Implement a Simplified CompletableFuture with Parallel Array Splitting
类型:online_judge
Problem: Design and Implement a Simplified CompletableFuture with Parallel Array Splitting
Design and implement a simplified variant of Java's CompletableFuture. For online judging, implement it in Python, but the design should reflect the core concurrency behavior of CompletableFuture.
You need to implement a simplified Future framework and use it to process an array in parallel.
Required Features
Implement SimpleCompletableFuture with at least the following capabilities:
supply_async(fn, executor)
Runs fn asynchronously in a thread pool.
Returns a future.
result()
Blocks until the asynchronous computation completes.
Returns the result if the task succeeds.
Re-raises the exception if the task fails.
then_apply(fn, executor)
After the current future completes successfully, asynchronously runs fn(previous_result) in the thread pool.
Returns a new future.
If the current future fails, the new future should also fail.
all_of(futures)
Waits for a list of futures to complete.
Returns a new future whose result is a list of all results in the same order as the input futures.
If any future fails, the returned future should fail as well.
Array Processing Requirement
Given an integer array nums:
Split it into contiguous chunks of size at most chunk_size.
Asynchronously compute the sum of squares for each chunk.
Wait for all chunk computations to complete.
Merge all partial results and output the total sum of squares.
That is, output:
sum(x * x for x in nums)
However, the computation must be performed using your simplified Future framework.
Input Format
n chunk_size max_workers
nums[0] nums[1] ... nums[n-1]
n: length of the array.
chunk_size: maximum size of each chunk.
max_workers: maximum number of worker threads.
The second line contains n integers.
Output Format
Print one integer: the sum of squares of all elements.
Constraints
0 <= n <= 100000
1 <= chunk_size <= max(1, n)
1 <= max_workers <= 64
-10^6 <= nums[i] <= 10^6
Example 1
Input:
5 2 2
1 2 3 4 5
Output:
55
Explanation: The chunks are [1, 2], [3, 4], and [5]. The total sum of squares is 1 + 4 + 9 + 16 + 25 = 55.
Example
Input
5 2 2
1 2 3 4 5
Output
55