wrand

package module
v0.0.0-...-59b8859 Latest Latest
Warning

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

Go to latest
Published: Dec 27, 2023 License: BSD-3-Clause Imports: 4 Imported by: 0

README

wrand - Weighted Random for Go

Test Go Reference

Example

weights := map[string]int{
    "A": 20,
    "B": 30,
    "C": 50,
}

rw, err := wrand.New(weights, nil)
if err != nil {
    fmt.Printf("error: %s", err)
    return
}

for i := 0; i < 5; i++ {
    fmt.Println(rw.Rand())
}

Documentation

Overview

Package wrand provide weighted random.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type WRand

type WRand[T comparable] struct {
	// contains filtered or unexported fields
}

WRand is weighted random generator.

Example
package main

import (
	"fmt"

	"github.com/tebeka/wrand"
)

func main() {
	weights := map[string]int{
		"A": 20,
		"B": 30,
		"C": 50,
	}

	rw, err := wrand.New(weights, nil)
	if err != nil {
		fmt.Printf("error: %s", err)
		return
	}

	for i := 0; i < 5; i++ {
		// We don't print here since the algorithm is not deterministic - flaky test.
		out := rw.Rand()
		if _, ok := weights[out]; !ok {
			fmt.Printf("error: unknown value - %q", out)
		}
	}

}
Output:

func New

func New[T comparable](weights map[T]int, r *rand.Rand) (WRand[T], error)

New returns WRand from weights. If r is nil, it'll create new rand.Rand from the current time.

func (WRand[T]) Rand

func (rw WRand[T]) Rand() T

Rand returns random element from the weighted population.

Jump to

Keyboard shortcuts

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