I am attempting to write a horse race simulator with multiple rows. Each row will represent one horse location calculated by a goroutine.
For some reason the code, when run on the Go Playground, does not output the numbers randomly as happens on my machine.
package main
import (
"math/rand"
"os"
"strconv"
"time"
)
var counter = 0
func main() {
i := 1
horses := 9
for i <= horses {
go run(i)
i++
}
time.Sleep(5000 * time.Millisecond)
print("\ncounter: " + strconv.Itoa(counter))
print("\nEnd of main()")
}
func run(number int) {
var i = 1
var steps = 5
for i <= steps {
print("[" + strconv.Itoa(number) + "]")
rand.Seed(time.Now().UnixNano())
sleep := rand.Intn(10)
time.Sleep(time.Duration(sleep) * time.Millisecond)
i++
counter++
}
if i == steps {
println(strconv.Itoa(number) + " wins")
os.Exit(1)
}
}
Playground: https://play.golang.org/p/pycZ4EdH7SQ
My output unordered is:
[1][5][8][2][3][4][7][9][6][7][9][9][4][3]...
But my question is how would I go about to print the numbers like:
[1][1]
[2][2][2][2][2][2][2][2]
[3][3][3]
...
[N][N][N][N][N]