在NetLogo中使用两个条件对补丁集或代理集进行排序

时间:2014-09-05 09:26:51

标签: sorting netlogo

我的补丁包含costgain个属性,我想对最小cost和最大gain的补丁列表进行排序。 sort-by函数用于对一个属性进行排序,但如何对这两个属性进行排序?

1 个答案:

答案 0 :(得分:2)

要对多个属性上的代理集进行排序,您可以使用sort-bysort-on

patches-own [ cost gain ]

to sort-patches
  ca
  ask patches [
    set cost random 100
    set gain random 100
  ]

  let patches-sorted-by sort-by [
    ([ cost ] of ?1 > [ cost ] of ?2) or
    ([ cost ] of ?1 = [ cost ] of ?2 and [ gain ] of ?1 < [ gain ] of ?2)
  ] patches
  show map [[ list cost gain ] of ? ] patches-sorted-by

  let patches-sorted-on sort-on [ (cost * -1000) + gain ] patches
  show map [[ list cost gain ] of ? ] patches-sorted-on
end

您喜欢哪一个取决于您。使用sort-on需要仔细构建您的公式(即,如果您的收益大于1000,则上述方法不起作用)但稍微不那么详细。

修改:对多个条件进行排序的更通用方法

好的,这对你的情况来说可能有点过头了,但我想出了一些更为通用的东西:

to-report sort-by-criteria [ criteria items ]
  ; `criteria` needs to be a task that returns a list of numbers
  report sort-by [
    compare-lists (runresult criteria ?1) (runresult criteria ?2)
  ] items
end

to-report compare-lists [ l1 l2 ]
  report ifelse-value (empty? l1 or empty? l2) [ false ] [
    ifelse-value (first l1 = first l2)
      [ compare-lists but-first l1 but-first l2 ]
      [ first l1 < first l2 ]
  ]
end

您需要传递的内容sort-by-criteriatask,如果您要对其中一个项目进行排序,则会报告一个数字列表,根据这些数字对您的项目进行排序。

在您的情况下,您可以使用它:

let sorted-patches sort-by-criteria (
  task [[ list (-1 * cost) gain ] of ? ]
) patches

对于两个标准,它可能不值得使用,但如果您有一长串标准,那么使用它可能比任何其他方法更容易和更清晰。