MoMo
MoMo

Reputation: 331

NetLogo: Assign Turtles Randomly but Equally to Different Groups

I used the code below to create 50 turtles and randomly assign them to one of four different strategies (i.e. a, b, c and d):

The problem is that when I decrease the number of created turtles or when I increase the number of strategies, I face a situation where at least one of the strategies is not taken by any turtle.

turtles-own [ my_strategy ]

to setup
  ;; create 50 turtles and assign them randomly
  ;; to one of four different strategies
  create-turtles 50 [
    set my_strategy one-of [ "a" "b" "c" "d" ]
  ]
end

I need your help here to: 1. Make sure that I do not face a situation where one or more strategies are not taken by any turtle. 2. Make sure that the number of turtles assigned to each strategy is roughly equal.

I tried to solve the problem by using the code below, but it did not work:

turtles-own [ my_strategy ]

to setup
  let strategies [ "a" "b" "c" "d" ]
  let turtles-num 51
  let i 0

  create-turtles turtles-num 

  while [ not any? turtles with [  my_strategy = 0 ] ] [
    ifelse i < length strategies - 1 [ set i i + 1 ] [ set i 0 ]
    ask n-of ceiling  ( turtles-num / length strategies ) turtles with [ my_strategy = 0 ] [
      set my_strategy item i strategies
    ]
  ]

Thank you for your help.

Upvotes: 0

Views: 307

Answers (1)

JenB
JenB

Reputation: 17678

In general, you should never use who numbers for anything in NetLogo. However, this is one of the very few occasions where it's appropriate.

From comments, you actually want equal (or as close to equal as possible) numbers in each group so you don't need to calculate the number in each group. When turtles are created, they are created with sequential who numbers. So you can use the mod operator to assign them to each strategy in turn.

turtles-own [ my_strategy ]

to setup
  ;; create 50 turtles and assign them equally
  ;; to one of four different strategies
  create-turtles 50 [
    set my_strategy item (who mod 4) [ "a" "b" "c" "d" ]
  ]
end

Upvotes: 3

Related Questions