Skip to content

Instantly share code, notes, and snippets.

Created December 10, 2012 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/4251470 to your computer and use it in GitHub Desktop.
Save anonymous/4251470 to your computer and use it in GitHub Desktop.
wirth-problem-15-12 in go
package main
import (
"log"
"sort"
)
func generateSet(c chan<- int) {
min := 0
nums := make([]int, 0)
nums = append(nums, 1)
for len(nums) > 0 {
// get the first num in slice. should be lowest num.
i := nums[0]
// have we already seen this number?
if i > min {
// nope, yield the number to the channel
c <- i
// update min so we'll skip this number if we have
// a dupe in the nums slice
min = i
// add the next two numbers in the set
nums = append(nums[1:], (2*i)+1, (3*i)+1)
// sort
sort.Ints(nums)
} else {
// already seen this number. pop first element off
// slice and keep going
nums = append(nums[1:])
}
}
}
// http://programmingpraxis.com/2012/12/07/wirth-problem-15-12/
func main() {
// this solution uses a channel and goroutine as a
// generator that yields the next value in the set
c := make(chan int)
go generateSet(c)
// print the first 100 numbers in the set
for i := 0; i < 100; i++ {
log.Println(i, <-c)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment