Hone logo
Hone
Problems

Go Generator Pattern: Iterating Over a Sequence

Generators are a powerful programming concept that allow you to create iterators in a memory-efficient way, especially when dealing with potentially large or infinite sequences. In Go, the generator pattern is typically implemented using channels. This challenge will guide you through building a simple generator to produce a sequence of numbers.

Problem Description

Your task is to implement a generator function in Go that produces a sequence of integers. This generator should accept a maximum value and return a channel from which the caller can receive the numbers. The generator should send numbers from 0 up to (but not including) the specified maximum value. Once all numbers have been sent, the channel should be closed to signal the end of the sequence.

Key Requirements:

  • Create a function generateNumbers(max int) that returns a <-chan int.
  • Inside generateNumbers, launch a goroutine that iterates from 0 up to max - 1.
  • In each iteration, send the current number to the returned channel.
  • After sending the last number, close the channel.
  • The caller will consume numbers from the channel using a for range loop.

Expected Behavior:

When generateNumbers(5) is called, the returned channel should yield the numbers 0, 1, 2, 3, and 4, in that order. After 4 is sent, the channel should be closed.

Examples

Example 1:

Input: max = 5
ch := generateNumbers(5)
for num := range ch {
    fmt.Println(num)
}
Output:
0
1
2
3
4

Explanation: The generateNumbers(5) function creates a channel and a goroutine. The goroutine sends 0, 1, 2, 3, and 4 to the channel. After sending 4, it closes the channel. The for range loop in the main function iterates over the channel, printing each received number until the channel is closed.

Example 2:

Input: max = 0
ch := generateNumbers(0)
for num := range ch {
    fmt.Println(num)
}
Output:
(nothing is printed)

Explanation: When max is 0, the loop condition (i < max) is immediately false. The goroutine sends no numbers and closes the channel immediately. The for range loop on an empty, closed channel terminates without executing its body.

Example 3:

Input: max = 1
ch := generateNumbers(1)
for num := range ch {
    fmt.Println(num)
}
Output:
0

Explanation: The generator sends only the number 0 and then closes the channel.

Constraints

  • The max parameter will be a non-negative integer.
  • The generator should handle max values from 0 up to 1000 without significant performance degradation or excessive memory usage.
  • The solution must utilize channels and goroutines to implement the generator pattern.

Notes

  • Remember that closing a channel signals that no more values will be sent.
  • A for range loop over a channel will automatically exit when the channel is closed.
  • Consider how to ensure the goroutine finishes its work and exits gracefully.
Loading editor...
go