Skip to content
Exercise · Goroutines and channels · lesson 11 of 13

Exercise: sum in goroutines

Write a function func parallelSum(nums []int, parts int, partSum func([]int) int) int. It splits nums into parts parts of consecutive elements, calls partSum once for each part in its own goroutine, and returns the sum of all the results.

The function partSum sums one part, but it is slow: it waits before answering, like a request to another server. So all the partSum calls must run at the same time, and the tests check this. Wait for the goroutines with sync.WaitGroup from lesson 2, or collect the results through a channel.

  • parallelSum([]int{1, 2, 3, 4}, 2, partSum) → 10
  • parallelSum([]int{1, 2, 3}, 5, partSum) → 6
  • parallelSum([]int{10, 20, 30, 40, 50, 60, 70, 80}, 4, partSum) → 360, and four partSum calls wait at the same time

Constraints: parts is at least 1 and may be greater than the length of nums; the length of nums is not always divisible by parts; numbers may be negative; for an empty nums the result is 0.

Part p (from 0) is nums[p*len(nums)/parts : (p+1)*len(nums)/parts]; when parts exceeds the length, some parts are empty.

The check runs the tests with the race detector: if goroutines change a shared variable, such as a shared total, without synchronisation, the solution fails.

Do not add extra imports unless the task says so explicitly.

sum.go — go
go · 6 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way