Search code examples
netlogo

How to create a sequential counter in NetLogo 6.2?


I would like to know if there is any way to implement a sequential counter without using a list by intervals. I'm trying to implement the following: at the end of each tick is counting the population size (NFinal). And then, we would check the constancy of the population, through a subtraction (the logical test would be the result of this subtraction is equal to zero during 3 consecutive ticks?).

For example:

NFinal of tick 0 - NFinal of tick 1 = 0
NFinal of tick 1 - NFinal of tick 2 = 0
NFinal of tick 2 - NFinal of tick 3 = 0

If this is the scenario (with 3 sequential values ​​equal to zero), the simulation will stop.

However, if it is in the scenario:

NFinal of tick 0 - NFinal of tick 1 = 0
NFinal of tick 1 - NFinal of tick 2 = 0
NFinal of tick 2 - NFinal of tick 3 = 2

The simulation does not stop (since it did not have 3 zero values ​​in sequence) and therefore would reset the counter to continue the simulation.

However what I managed to implement was by intervals using list. I don't know if it's the best way. Well, every time I use the list my model is getting slower. Is there a simpler way to implement this?

Thanks in advance!

Attempt below:

globals [ StabilityList ConstanceInterval ]

to go
  if ConstanceInterval = 0 [ stop ]
end
  
to StabilityCheckerProc  
  set StabilityList lput 1 StabilityList  ;; 1 = NFinal
  let i 3 ;; 
  if length StabilityList >= i
  [
    let t1 last StabilityList    
    let start ( length StabilityList - i ) 
    let t0 item start StabilityList
    set ConstanceInterval abs ( t1 - t0 )       
  ] 
  set StabilityList get-last i StabilityList 
end

to-report get-last [ num lst ]
  let b length lst
  let a b - num
  report sublist lst ( ifelse-value ( a < 0 ) [ 0 ] [ a ] ) b
end

Solution

  • You could use a counter to track the number of occurrences in a row, such that if your condition is satisfied you increase the counter, and if it is not you reset the counter. For example:

    globals [ zero-tracker ]
    
    to setup
      ca
      reset-ticks
    end
    
    to go 
      let variable-placeholder random 5
      ifelse variable-placeholder = 0 [
        ; If a zero is recorded (eg, the result of your subtraction operation, 
        ; increase the zero-tracker by one
        set zero-tracker zero-tracker + 1
      ]  [
        ; If anything BUT a zero is recorded, reset the zero-tracker
        set zero-tracker 0
      ]
      tick
      if zero-tracker = 3 [
        stop
      ]
    end