Go: Sum in two halves

Two goroutines can each do half of a job.

What to build

A program that adds a list of numbers with two goroutines.

Requirements

  • Read n, then n whole numbers. Split the list at the middle (n / 2 numbers go to the left half).
  • Start one goroutine for each half; each sends the sum of its half through a channel.
  • Print left: L, right: R and total: T.

Input

Line 1: n. Then n whole numbers.

Output

Three lines.

Constraints

1 ≤ n ≤ 1000; each number is between -1000 and 1000.

Example

Input:

6
1 2 3 4 5 6

Output:

left: 6
right: 15
total: 21

Why it works

Each goroutine works on its own half and sends one result. Reading from the channels waits until both results are ready, so the printed values are always the same.

Examples

Example 1 · Input
6
1 2 3 4 5 6
Expected output
left: 6
right: 15
total: 21
Example 2 · Input
3
10 -20 30
Expected output
left: 10
right: 10
total: 20

Hints

Hint 1

Split the slice into nums[:mid] and nums[mid:] and start a goroutine for each half.

Hint 2

Each goroutine sends its sum on its own channel; read both channels in main.

Solution

Show one correct solution (try it yourself first)
package main

import "fmt"

func sum(nums []int, out chan int) {
	total := 0
	for _, v := range nums {
		total += v
	}
	out <- total
}

func main() {
	var n int
	fmt.Scan(&n)
	nums := make([]int, n)
	for i := range nums {
		fmt.Scan(&nums[i])
	}
	mid := n / 2
	left := make(chan int)
	right := make(chan int)
	go sum(nums[:mid], left)
	go sum(nums[mid:], right)
	l, r := <-left, <-right
	fmt.Println("left:", l)
	fmt.Println("right:", r)
	fmt.Println("total:", l+r)
}

▶ Open this solution in the compiler

Lesson: Goroutines and channels →