Netlogo: Assign variable using probabilities

后端 未结 2 1938
北恋
北恋 2020-12-17 01:16

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

2条回答
  •  执笔经年
    2020-12-17 01:35

    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.

提交回复
热议问题