How to assign a string or integer variable to turtle, using probabilities of the variables in a group/list? For example it is 0.4 probability that one specific variable is u
is there a better way?
Yes there is.
NetLogo 6.0 comes with the rnd extension bundled. (You can also download the extension separately for earlier versions of NetLogo.)
The rnd
extension offers the rnd:weighted-one-of-list primitive, which does exactly what you're trying to do:
extensions [ rnd ]
to-report pick
let probabilities [0.1 0.2 0.4 0.3]
let some_list ["String1" "String2" "String3" "String4"]
report first rnd:weighted-one-of-list (map list some_list probabilities) last
end
Let me unpack the last expression a bit:
The role of (map list some_list probabilities)
is to "zip" the two lists together, in order to get a list of pairs of the form: [["String1" 0.1] ["String2" 0.2] ["String3" 0.4] ["String4" 0.3]]
.
That list of pairs is passed as the first argument to rnd:weighted-one-of-list
. We pass last
as the second argument of rnd:weighted-one-of-list
to tell it that it should use the second item of each pair as the probability.
rnd:weighted-one-of-list
then picks one of the pairs at random, and returns that whole pair. But since we're only interested in the first item of the pair, we use first
to extract it.
To understand how that code works, it helps to understand how Anonymous procedures work. Note how we make use of the concise syntax for passing list
to map
and for passing last
to rnd:weighted-one-of-list
.
Don't overlook the rnd
extension:
https://github.com/NetLogo/Rnd-Extension
But it is possible to do it essentially as you propose. I'll to that here, but it would be better to use explicit arguments.
to-report random-pick
let _r random-float 1
let _ps [0.1 0.2 0.4 0.3]
let _lst ["String1" "String2" "String3" "String4"]
let _i 0
while [_r >= item _i _ps] [
set _r (_r - item _i _ps)
set _i (_i + 1) ]
report item _i _lst
end