UserBRy
UserBRy

Reputation: 359

How to find and save the sum of a variable from a specific list of turtles, Netlogo?

How would you find the sum a turtle specific variable from a list of turtles?

I'm trying to sum a variable from a list of turtles and compare that sum to the asking turtle's specific value, but I'm not sure what the syntax would be.

Each turtle has it's own specific list composed of other turtles to ask [mylist], and I'm looking to sum their var_x and compare it to the asking turtle's var_x.

ask turtles [
set ListVarXSum ( sum (var_x) of each turtle on list [mylist] )
]

Upvotes: 0

Views: 343

Answers (2)

Nicolas Payette
Nicolas Payette

Reputation: 14972

The most direct way to do what you want is:

set ListVarXSum sum map [ t -> [ var-x ] of t ] mylist

The map primitive transforms the list of turtles into a list filled by the values of var-x for each of those turtles. You can then sum that list with sum.

That being said, Luke C is right that it's often more convenient to store agents in a agentset then in a list (unless you need them to be in a specific order or you have repeated agents).

To convert a list of agents into an agentset, you can always use the turtle-set primitive. Using that, you could do:

set ListVarXSum sum [ var-x ] of turtle-set mylist

It reads nicer, but it runs slower because of the time needed to convert the list into an agentset every time. If it's an operation you need to do often, it's probably better to store an agentset up front (possibly by using turtle-set to convert whatever it is that you are putting in mylist into an agentset instead, or by using a primitive that gives you an agentset anyway, like Luke's n-of example.)

Upvotes: 3

Luke C
Luke C

Reputation: 10301

If I understand what you're after, it might be easiest to not use a list of turtles but to use an agentset of the turtles to compare against instead. Have a look at this simple example and see if it accomplishes what you need:

turtles-own [ 
  var_x 
  my_comparison_turtles 
]

to setup
  ca
  crt 10 [
    set var_x 3 + random 10
    setxy random-xcor random-ycor
  ]

  ask turtles [
    set my_comparison_turtles n-of 3 other turtles
  ]
  reset-ticks
end

to sum-compare

  ask turtles [
    let temp_sum sum [var_x] of my_comparison_turtles
    print ( word "My var_x is " var_x ", and the sum of my comparison turtles' var_x is " temp_sum "." )
  ]

end

Upvotes: 2

Related Questions