rnd:weighted-one-of-list
rnd:weighted-one-of-list list anonymous-reporter
Reports a random item from list.
The probability of each item being picked is proportional to the weight given by the anonymous-reporter for that item. The weights must not be negative. The first argument passed to the anonymous procedure refers to the list item. (See the Anonymous Procedures section of the Programming Guide for more details.)
It is an error for the list to be empty.
A common way to use the primitive is to have a list of lists, where the first item of each sublist is the thing you want to choose and the second item is the weight. Here is a short example:
let pairs [ [ "A" 0.2 ] [ "B" 0.8 ] ]
repeat 25 [
; report the first item of the pair selected using
; the second item (i.e., `last p`) as the weight
type first rnd:weighted-one-of-list pairs [ [p] -> last p ]
]
This should print B
roughly four times more often than it prints A
.
If you happen to have your items and your weights in two separate lists, you can combine them into pairs by using a combination of map
and list
:
let items [ "A" "B" "C" ]
let weights [ 0.1 0.2 0.7 ]
let pairs (map list items weights)
Since we apply map
to both the items
list and the weights
list, the parentheses are needed in (map list items weights)
. We also use the concise anonymous procedure syntax (see the programming guide) to pass list
as the reporter for map
. The same thing could have been written (map [ [a b] -> list a b ] items weights)
.
Take me to the full Rnd Extension Dictionary