title: NetLogo: Asking a limited number of turtles, ranked by the value of a variable
body: <p>I am trying to model capacity constraints and priorities in NetLogo (5.3.1, on Mac Sierra). It comes down to asking a limited number of turtles (say <code>n</code>) to do certain things, and choosing those turtles so that (1) they satisfy a certain conditios and (2) they are the <code>n</code> turtles with the maximum value of variable <code>my-variable</code>. </p>
  
  <p>I am trying to do this by:</p>
  
  <pre><code>let subset-of-turtles turtles with [ condition-variable = some-value ]
  ask max-n-of n subset-of-turtles [ my-variable ] [&lt; do something &gt;]
  </code></pre>
  
  <p>But it has multiple issues. </p>
  
  <p>First, if no turtle satisfies the condition that <code>[ condition-variable = some-value ]</code>, NetLogo throws up an error </p>
  
  <blockquote>
    <p>Requested n random agents from a set of only 0 agents.</p>
  </blockquote>
  
  <p>I tried solving by inserting a line before the <code>ask</code> command:</p>
  
  <pre><code>let subset-of-turtles turtles with [ condition-variable = some-value ]
  if subset-of-turtles != nobody [
    ask max-n-of n subset-of-turtles [ my-variable ] [&lt; do something &gt;]
    ]
  </code></pre>
  
  <p>But it does not work:</p>
  
  <pre><code>observer&gt; show turtles with [ condition-variable = some-value ]
  observer: (agentset, 0 turtles)
  observer&gt; let subset-of-turtles turtles with [ condition-variable = some-value ] show subset-of-turtles != nobody
  observer: true 
  </code></pre>
  
  <p>NetLogo considers that an empty agentset is still an agentset, so it will pass the test of being different from <code>nobody</code>.</p>
  
  <p>Second, even when there are some turtles that do meet the condition, NetLogo will throw up the same error if they are fewer than <code>n</code>. My model is a growth model, in which capacity is meant to be sufficient at the beginning, and then to hit the constraint. So, this will happen in every single run of the model. </p>
  
  <p>I would like NetLogo to execute the command in the <code>ask</code> block at most <code>n</code> times. Suppose there are <code>m</code> turtles that satisfy the condition:
   1. If <code>m &lt;= n</code>, execute the command on all <code>m</code> turtles
   2. <code>If m &gt; n</code>, execute the command of the <code>n</code> turtles with the highest values of <code>my-variable</code>. Can anybody advise?    </p>