Zahzah
Zahzah

Reputation: 81

Tie breaker in Netlogo sorting process

I want to sort the turtles according to their "var" values. My code is:

globals [liste]
turtles-own [var]
to setup
clear-all
create-turtles 5 [setxy (random 5) (random 5)]
ask turtle 0 [set var 1]
ask turtle 1 [set var 1]
ask turtle 2 [set var 1]
ask turtle 3 [set var 2]
ask turtle 4 [set var 3]

set liste [who] of turtles
set liste sort-by [([var] of turtle ?1) < ([var] of turtle ?2)] liste
show liste

end

This code is working and I obtain the following results during several exceutions

observer: [0 2 1 3 4]

observer: [1 0 2 3 4]

observer: [0 2 1 3 4]

The problem that is I want that the sorting process returns always the same results. From my point of view, it is possible to add a tie breaker, but I don't know how to do it in Netlogo. Any suggestions?

Upvotes: 1

Views: 88

Answers (1)

mattsap
mattsap

Reputation: 3806

You could create your own custom reporter that considers the tie breaker. Below, I create a turtle-compare reporter which checks if the vars are equal, if so, they compare based on the who (a guaranteed unique identifier as the tie breaker). Otherwise, the turtles are compared by the variable you specified.

I would like to note, you could just pass in the turtles directly, rather than a list of their whos.

to setup
    ...
    show sort-by turtle-compare turtles
    ...
end

to-report turtle-compare [t1 t2]
  report ifelse-value ([var] of t1 = [var] of t2)
  [[who] of t1 < [who] of t2]
  [[var] of t1 < [var] of t2]
end

Upvotes: 1

Related Questions