Go: A three-stage pipeline

Goroutines connected by channels make a pipeline in which every stage does one small job.

What to build

A program that builds a pipeline: numbers, squares, then a filter, and adds up what is left.

Requirements

  • Read n and k.
  • Stage 1 sends the numbers 1 to n. Stage 2 sends the square of each number as an int64. Stage 3 passes on only the squares divisible by k.
  • The main function reads the last channel until it is closed, and prints count C and sum S for the squares that passed.

Input

One line with n and k.

Output

Two lines.

Constraints

1 ≤ n ≤ 1000; 1 ≤ k ≤ 100.

Example

Input:

10 4

Output:

count 5
sum 220

Why it works

Each stage is a function that returns a channel and closes it when its input is closed, so the closing travels down the pipeline and range in main ends at the right time. The order of the values stays the same because every stage handles one value at a time.

Examples

Example 1 · Input
10 4
Expected output
count 5
sum 220
Example 2 · Input
5 1
Expected output
count 5
sum 55

Hints

Hint 1

Write generate(n) that returns a channel of 1..n, square(in) that returns a channel of squares as int64, and keep(in, k) that passes only multiples of k.

Hint 2

Each stage starts a goroutine and closes its output channel when its input is finished.

Solution

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

import "fmt"

func generate(n int) <-chan int {
	out := make(chan int)
	go func() {
		for i := 1; i <= n; i++ {
			out <- i
		}
		close(out)
	}()
	return out
}

func square(in <-chan int) <-chan int64 {
	out := make(chan int64)
	go func() {
		for v := range in {
			out <- int64(v) * int64(v)
		}
		close(out)
	}()
	return out
}

func keep(in <-chan int64, k int64) <-chan int64 {
	out := make(chan int64)
	go func() {
		for v := range in {
			if v%k == 0 {
				out <- v
			}
		}
		close(out)
	}()
	return out
}

func main() {
	var n, k int
	fmt.Scan(&n, &k)
	count := 0
	var sum int64
	for v := range keep(square(generate(n)), int64(k)) {
		count++
		sum += v
	}
	fmt.Println("count", count)
	fmt.Println("sum", sum)
}

▶ Open this solution in the compiler

Lesson: Goroutines and channels →