Poor title, but I didn't know how else to describe it within the character limit.
As a learning exercise, I'm trying to write a little Go program that simulates a lottery draw. It draws six random numbers to be the winning set, then continually draws random arrays of random ints until you get that set again.
First I wrote a function which takes a channel and infinitely loops "add array of 6 random ints to the channel":
func draw(ch chan<- [6]int) {
generator := rand.New(rand.NewSource(time.Now().UnixNano()))
for {
ch <- [6]int{
generator.Intn(100),
generator.Intn(100),
generator.Intn(100),
generator.Intn(100),
generator.Intn(100),
generator.Intn(100),
}
}
}
Then in main()
I specify two OS threads, create a channel that can hold 250 arrays of 6 ints, and start my draw()
function in a goroutine.
runtime.GOMAXPROCS(2)
ch := make(chan [6]int, 250)
go draw(ch)
Next I take a winning set (eg [4 8 15 16 23 42]
) from the channel, then a 'current' set, meaning the most recent draw. I set my game_played counter to 1:
winning := <- ch
current := <- ch
games_played := 1
Here's the tricky bit.
In an infinite loop, I check if the current draw is equal to the winning draw. If it is, I print the number of games played, and break from the loop.
If it isn't, I set current
to a new draw, and increment the counter. The loop should then run the if winning == current...
check again over and over until there's a match.
for {
if winning == current {
fmt.Println(games_played)
break
} else {
current := <- ch
games_played += 1
}
}
Here's the problem: that fourth-last line, current := <- ch
, throws a compiler error, 'current declared and not used'. I want to say "Yeah, I know it's not used after that point reading downward, but it's declared inside a loop, so its value matters on the next iteration." But I can't work out how, or if I've done something stupid. I'm totally clueless about Go, obviously. But to me, thinking through it, the logic is sound. Am I messing something up?
(Note: I'm aware of the oversight that a draw of [1 2 3]
won't be equal to [2 3 1]
, ignoring that for now.)