public
anonymous / problem_15_12.go
Created

wirth-problem-15-12 in go

  • Download Gist
problem_15_12.go
Go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
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)
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.