yrand

package
Version: v0.0.0-...-a823632 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2020 License: MIT Imports: 7 Imported by: 7

Documentation

Overview

Package yrand is yet another wrapper of cryptographically secure random number generator.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// QuitShuffle is used as a return value from ShuffleIndexFunc to indicate that the execution of WeightedShuffle should be terminated immediately.
	// It is not returned as an error by any function.
	//nolint:golint // this is not a real error returned by any functions, it works as a flag instead.
	QuitShuffle = errors.New("quit this shuffle")
)

Functions

func ChoiceInt

func ChoiceInt(list []int) (n int, err error)

ChoiceInt returns a random element from the non-empty slice of int.

func ChoiceString

func ChoiceString(list []string) (s string, err error)

ChoiceString returns a random element from the non-empty slice of string.

Example

This example chooses a random food from a given list.

package main

import (
	"fmt"

	"github.com/1set/gut/yrand"
)

func main() {
	foods := []string{
		"Ahi Poke",
		"Bouillabaisse",
		"Hukilau Chowder",
		"Kalua Pork",
		"Lau lau",
		"Lobster Casarecce",
		"Loco Moco",
		"Manapua",
	}
	food, err := yrand.ChoiceString(foods)
	if err != nil {
		fmt.Println("got error:", err)
		return
	}

	fmt.Println("I 🍴", food)
}
Output:

func Float32

func Float32() (n float32, err error)

Float32 returns a random float32 number in [0.0, 1.0).

func Float64

func Float64() (n float64, err error)

Float64 returns a random float64 number in [0.0, 1.0).

Example

This example simulates coin toss experiments

package main

import (
	"fmt"

	"github.com/1set/gut/yrand"
)

func main() {
	head, tail := 0, 0
	count := 100000
	for i := 0; i < count; i++ {
		n, err := yrand.Float64()
		if err != nil {
			fmt.Println("got error:", err)
			return
		}
		if n < 0.5 {
			head++
		} else {
			tail++
		}
	}

	fmt.Printf("Head: %d\nTail: %d\nRate: %.3f", head, tail, float64(head)/float64(tail))
}
Output:

func Int32Range

func Int32Range(min, max int32) (n int32, err error)

Int32Range returns a random int32 number in [min, max).

func Int64Range

func Int64Range(min, max int64) (n int64, err error)

Int64Range returns a random int64 number in [min, max).

Example

This example generates a random 6-digit PIN.

package main

import (
	"fmt"

	"github.com/1set/gut/yrand"
)

func main() {
	min, max := int64(0), int64(1000000)
	pin, err := yrand.Int64Range(min, max)
	if err != nil {
		fmt.Println("got error:", err)
		return
	}

	fmt.Printf("PIN: %06d\n", pin)
}
Output:

func IntRange

func IntRange(min, max int) (n int, err error)

IntRange returns a random int number in [min, max).

Example

This example chooses a random fish from a given list.

package main

import (
	"fmt"

	"github.com/1set/gut/yrand"
)

func main() {
	fishes := []string{
		"Ahi",
		"Basa",
		"Kajiki",
		"Mahi Mahi",
		"Monchong",
		"Salmon",
		"Tilapia",
		"Tuna",
	}
	idx, err := yrand.IntRange(0, len(fishes))
	if err != nil {
		fmt.Println("got error:", err)
		return
	}

	fish := fishes[idx]
	fmt.Println("I 🥰", fish, "🐠")
}
Output:

func Runes

func Runes(alphabet string, length int) (s string, err error)

Runes returns a random string of given length with given Unicode chars only.

func Shuffle

func Shuffle(n int, swap ShuffleSwapFunc) (err error)

Shuffle randomizes the order of elements.

n is the number of elements. swap swaps the elements with indexes i and j.

The algorithm is the Fisher-Yates Shuffle and its complexity is O(n).

Example

This example randomizes the order of a list of numbers.

package main

import (
	"fmt"

	"github.com/1set/gut/yrand"
)

func main() {
	num := []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29}
	swapFunc := func(i, j int) {
		num[i], num[j] = num[j], num[i]
	}
	fmt.Println("before:", num)

	count := len(num)
	if err := yrand.Shuffle(count, swapFunc); err != nil {
		fmt.Println("got error:", err)
		return
	}
	fmt.Println("after: ", num)
}
Output:

func String

func String(alphabet string, length int) (s string, err error)

String returns a random string of given length with given ASCII chars only.

func StringBase36

func StringBase36(length int) (s string, err error)

StringBase36 returns a random string of given length with A-Z0-9 chars only.

Example

This example generates a random string of 20 A-Z0-9 chars.

package main

import (
	"fmt"

	"github.com/1set/gut/yrand"
)

func main() {
	key, err := yrand.StringBase36(20)
	if err != nil {
		fmt.Println("got error:", err)
		return
	}

	fmt.Println("Key:", key)
}
Output:

func StringBase62

func StringBase62(length int) (s string, err error)

StringBase62 returns a random string of given length with a-zA-Z0-9 chars only.

func StringLetters

func StringLetters(length int) (s string, err error)

StringLetters returns a random string of given length with A-Z chars only.

func Uint32Range

func Uint32Range(min, max uint32) (n uint32, err error)

Uint32Range returns a random uint32 number in [min, max).

func Uint64Range

func Uint64Range(min, max uint64) (n uint64, err error)

Uint64Range returns a random uint64 number in [min, max).

func UintRange

func UintRange(min, max uint) (n uint, err error)

UintRange returns a random uint number in [min, max).

func WeightedChoice

func WeightedChoice(weights []float64) (idx int, err error)

WeightedChoice selects a random index according to the associated weights (or probabilities).

Indexes with zero or negative weight value will be ignored.

The slice of associated weights must contain at least one positive value.

The complexity is O(n) where n = len(weights).

Example

This example chooses a random person according to associated weights.

package main

import (
	"fmt"

	"github.com/1set/gut/yrand"
)

func main() {
	var (
		candidates = []string{"Knuth", "Morris", "Pratt"}
		weights    = []float64{0.8, 0.1, 0.1}
	)
	idx, err := yrand.WeightedChoice(weights)
	if err != nil {
		fmt.Println("got error:", err)
		return
	}
	fmt.Println("Luckiest Guy:", candidates[idx])
}
Output:

func WeightedShuffle

func WeightedShuffle(weights []float64, yieldFunc ShuffleIndexFunc) (err error)

WeightedShuffle randomizes the order of elements according to the associated weights (or probabilities).

All values in the slice of associated weights must be positive, and values of very different magnitudes are unacceptable.

The yieldFunc will be called for each randomly selected index.

The complexity is O(n^2) where n = len(weights).

Example

This example chooses three random emojis according to associated weights.

package main

import (
	"fmt"

	"github.com/1set/gut/yrand"
)

func main() {
	var (
		emojis  = []string{"🍔", "🥪", "🌮", "🌯", "🥞", "🍪", "🥮", "🥠"}
		weights = []float64{8, 7, 6, 5, 2, 2, 1, 1}
		count   = 0
	)
	err := yrand.WeightedShuffle(weights, func(idx int) (err error) {
		fmt.Print(emojis[idx], " ")
		if count++; count == 3 {
			fmt.Println()
			err = yrand.QuitShuffle
		}
		return
	})
	if err != nil {
		fmt.Println("got error:", err)
		return
	}
}
Output:

Types

type ShuffleIndexFunc

type ShuffleIndexFunc func(idx int) (err error)

ShuffleIndexFunc is the type of the function called for each random index selected by WeightedShuffle.

If the function returns QuitShuffle, WeightedShuffle skips the rest and terminates immediately.

type ShuffleSwapFunc

type ShuffleSwapFunc func(i, j int)

ShuffleSwapFunc is the type of the function called by Shuffle to swap the elements with indexes i and j.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL