ranrot-b-pseudo random number generator


See On Github

Data

Contributor

Generic placeholder thumbnail

by jcla1

in go

Tags

cipher

Source Code

package ranrotb

// Call with seed and it will return a closure
// which will return pseudo-random numbers on
// consecutive calls
// Note: seed could be uint32(time.Now().Unix())
func RRBRand(seed uint32) func() uint32 {
	var lo, hi uint32

	// In Go ^ is the bitwise complement operator
	// In C this would be the tilde (~)
	lo, hi = seed, ^seed

	return func() uint32 {
		hi = (hi << 16) + (lo >> 16)
		hi += lo
		lo += hi
		return hi
	}
}
package ranrotb

import (
	"fmt"
	"time"
)

func Example() {
	r := rrbRand(uint32(time.Now().Unix()))
	m := make(map[uint32]int, 10)
	for i := 0; i < 100000; i++ {
		n := r() % 10

		if _, ok := m[n]; !ok {
			m[n] = 1
		} else {
			m[n] += 1
		}
	}

	fmt.Println(m)
}