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 used from specific group/list. The function selects randomly the variable based on probability. I need to use the same method afterwards to choose a variable (string) from a list according to probability. In python it should be:
import random
def random_value(probability_list, values):
r = random.random()
index = 0
while(r >= 0 and index < len(probability_list)):
r -= probability_list[index]
index += 1
value=values[index - 1]
value_index=index-1
return value,value_index
I tried it in Netlogo like below (get error that index is -1) but is there a better way?
globals [random_nr probabilities some_list index]
to initialize-variables
set some_list[]
set probabilities[]
end
to random_pick
set random_nr random-float 1
set probabilities [0.1 0.2 0.4 0.3]
set some_list ["String1" "String2" "String3" "String4"]
set index 0
while [(random_nr >= 0) and (length probabilities < index)] [
set random_nr random_nr - item index probabilities
set index index + 1 ]
set index index - 1
end
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.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 thernd:weighted-one-of-list
primitive, which does exactly what you're trying to do: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 passlast
as the second argument ofrnd: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 usefirst
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
tomap
and for passinglast
tornd:weighted-one-of-list
.