OC2PS
OC2PS

Reputation: 1069

How to find the average distance from turtles that fulfill a certain condition?

I want to move the current turtle one step closer to the others that fulfill a certain condition (e.g. have color = green).

I am doing this the hard way (because I don't know any better), by trying to calculate the the average distance of the current turtle from all others that fulfill the condition, and calculate the average from x+1, x-1, y+1, y-1. Then whichever is the smallest would indicate the direction of the move. Not very elegant, I know, and limits movements to horizontal and vertical, but I couldn't come up with anything better (the only other idea that struck me was to calculate average x and y coordinates of all turtles that fulfill the condition and move the current turtle towards that, but that seemed even more ridiculous to me)

Problem is that even with my clumsy solution, I am not getting anywhere, since I am struggling with how to calculate the average distance from the "green" turtles.

Upvotes: 0

Views: 147

Answers (1)

Luke C
Luke C

Reputation: 10301

If you want to calculate the mean distance, you can have the asking turtle call mean and [distance myself].

With this setup:

to setup
  ca 
  crt 10 [
    set color green
    move-to one-of patches with [ pxcor < 0 ]
  ]
  crt 1 [
    set color red
    move-to one-of patches with [ pxcor > 10 ]
  ]
  reset-ticks
end

Calling the function below will have the red turtle print out first all distances between itself and all green turtles, then the mean of those distances:

to calc-mean-distance
  ask turtles with [ color = red ] [
    print [ distance myself ] of turtles with [ color = green ]
    print mean [ distance myself ] of turtles with [ color = green ]
  ]
end

Beyond that, I'm not 100% sure what you're trying to do- are you hoping to move the asking turtle towards the nearest turtle that meets some condition? If so, this might work for you:

to go 
  ask turtles with [ color = red ] [
    let target min-one-of ( turtles with [ color = green ] ) [ distance myself ] 
    face target
    ifelse distance target > 1 [
      fd 1
    ] [
      move-to target
    ]
  ]
  tick
end

If you want the asking turtle to move instead towards the geographic center of those turtles that meet a condition, you could indeed get the mean x and y coordinates of those turtles as you describe, then have the asking turtle move towards that point:

to go
  let central-x mean [ xcor ] of turtles with [ color = green ]
  let central-y mean [ ycor ] of turtles with [ color = green ]
  ask turtles with [ color = red ] [
    facexy central-x central-y
    ifelse distancexy central-x central-y > 1 [
      fd 1 
    ] [
      setxy central-x central-y
    ]
  ]
  tick
end

If those aren't quite what you're trying to achieve, feel free to leave a comment for clarification!

Upvotes: 1

Related Questions