wrand

package module
v0.0.0-...-8c3f764 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2015 License: MIT Imports: 3 Imported by: 2

README

wrand

Go library for weighted random selection.

Documentation

Overview

Package wrand provides a way to choose random items where each item has it's own weight. For example if item "a" has weight 1 and item "b" has weight 2 then "b will be selected about twice as often as "a".

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SelectIndex

func SelectIndex(weights []float64) int

SelectIndex takes a list of weights and returns an index with a probability corresponding to the relative weight of each index. Behavior is undefined if len(weights) == 0. A weight of 0 will never be selected unless all are 0, in which case any index may be selected. Negative weights are multiplied by -1.

Types

type Item

type Item interface {
	Weight() int
	WeightIs(int)
	CumWeight() int
	CumWeightIs(int)
}

The Item type holds the user's value

type Object

type Object struct {
	// contains filtered or unexported fields
}

The Object type is the collection that holds all the items choose from.

func NewObject

func NewObject(inverse bool) *Object

NewObject creates and returns a new Object to work with. If inverse is true then smaller weights are more likely.

func (*Object) NewItem

func (o *Object) NewItem(item Item)

NewItem adds a new Item to the Object with ithe given value and weight.

func (*Object) RandomItem

func (o *Object) RandomItem() Item

RandomItem returns a random Item out of the ones that have been added via NewItem taking into account the weights of each item.

func (*Object) UpdateItemWeight

func (o *Object) UpdateItemWeight(item Item, weight int)

UpdateItemWeight sets the given Item's weight to the value provided. You should use this instead of setting the Item's weight yourself.

Jump to

Keyboard shortcuts

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