2014-09-05 92 views
1
兩個條件

我的補丁有costgain屬性,我想用最小的cost和最大gain排序補丁列表。 sort-by函數用於對一個屬性進行排序,但我如何排序這兩個屬性?排序補丁集或agentset用的NetLogo

+0

你能更準確地知道你想要的「最低成本和最大收益」是什麼意思?我可以想象幾種可能的含義 - 你可以從另一種中減去一種含義,或者只使用後者來打破前者中的聯繫,或者... – 2014-09-06 14:38:09

回答

1

排序許多屬性的agentset,您可以使用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-criteria是一個task,給定你想要排序的項目之一,將報告一個數字列表,根據該列表你的項目將被排序。

在你的情況,你會使用它想:

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

對於兩個標準,它可能不值得使用,但如果你有標準的長列表,它很可能是一個更容易和更清晰使用比其他任何方法。

+0

這假定只有成本相等才能獲得收益。但是我想知道這張海報是否真的需要考慮到這一點。 – 2014-09-06 17:18:43

+0

確實如此。我沒有考慮過這種選擇,但我想如果海報想要某種加權排序的成本和收益,他可以使用'sort-on'版本並用'(cost * -1000)+ gain'替換一個合適的功能。 – 2014-09-06 18:08:10

+0

謝謝Nicolas,謝謝Seth,實際上我想找到'cost'和'gain'之間的最佳組合......不僅如果成本是相等的。 – delaye 2014-09-08 08:16:00