Created
December 10, 2012 16:01
-
-
Save anonymous/4251470 to your computer and use it in GitHub Desktop.
wirth-problem-15-12 in go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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