YaK:: rolling a die [Changes]   [Calendar]   [Search]   [Index]   [PhotoTags]   
[mega_changes]
[photos]

rolling a die


$ cat simulate-dice.go
package main

import (
	"crypto/rand"
	"fmt"
	"math/big"
)

const SIX = 6
const NROLLS = 8194

const NTRIALS = 10000
const WAYOFF = 264

func Roll() int {
	six := big.NewInt(SIX)
	roll, err := rand.Int(rand.Reader, six)
	if err != nil { panic(err) }
	return int(roll.Int64())
}

func Trial() int {
	var pairs [SIX][SIX]int
	for i := 0; i < NROLLS; i++ {
		preroll := i % SIX;  // TODO: NROLLS is not divisible by 6.
		roll := Roll();
		pairs[preroll][roll]++
	}
	max := 0
	for i := 0; i < SIX; i++ {
		for j := 0; j < SIX; j++ {
			if pairs[i][j] > max {
				max = pairs[i][j]
			}
		}
	}
	return max
}

func main() {
	wayoff := 0
	for i := 0; i < NTRIALS; i++ {
		max := Trial();
		// fmt.Printf("%d: %d\n", i, max)
		if max >= 264 {
				wayoff++
		}
	}
	fmt.Printf("%d / %d = %.6f%% were way off.\n",
			wayoff, NTRIALS,
			float64(wayoff) / float64(NTRIALS) * 100.0);
}


$ time go run simulate-dice.go
1705 / 10000 = 17.050000% were way off.

real	1m38.216s
user	1m39.623s
sys	0m1.054s



(unless otherwise marked) Copyright 2002-2014 YakPeople. All rights reserved.
(last modified 2019-07-08)       [Login]
(No back references.)