在列表中选择一个元素

时间:2020-01-27 23:57:01

标签: netlogo

我有一个由两只乌龟组成的列表(为简单起见,houseslandlords)。 由于这里提供了一些建议,我从清单中选择了价格最高的房屋,但不幸的是房东不是那间房屋的所有者,而是只选择了一只tick。 我知道这只乌龟的定义出了点问题。 根据建议,我写的是:

    let selected_house max-one-of turtle-set my-list [price]
    let selected_landlord [my-landlord] of selected_house
       print (word "Landlord" [selected_landlord] of selected_house)
    let new_list (list selected_house selected_landlord)

       print (word  "Landlord " selected_landlord "of house: " selected_house " by price: " [price] of selected_house)

但是,如果我有:

列表:

"Landlord 2 is the owner of house 4 by price 400000"
"Landlord 5 is the owner of house 1 by price 100000"
"Landlord 4 is the owner of house 3 by price 300000" 

然后我使用selected_house/landlord选择价格最高的房屋的所有者,我应该得到(house 4, landlord 2);但是,我收到(house 4, landlord 5),即房东选择了一个刻度。

我对房东和房屋的定义如下(我有类似的练习,但是主题不同):

if breed = landlords [

          hatch-houses n_house [

            set price precision (random-float 1) 3

            set this-house self
            set this-landlord myself

            ask myself [

              set my-list fput (list this-house this-landlord) my-list

            ]
        ]

其中this-housethis-landlord是全局变量,而my-listlandlords' own

能否请您帮助我理解和解决此部分代码中的问题?

我认为,当我使用第一个元素=房子和第二个元素=房东创建列表时,有可能添加一些条件以使选择尽可能容易(例如,一旦选择了第一个元素(即价格最高的房屋),将列表中每个元素的第二项设置为房屋的房东)。

1 个答案:

答案 0 :(得分:2)

我不确定this-housethis-landlord为何是全局变量,并且我认为(可能没有完整的代码)这可能是您的问题。如果我了解您的模型,则每个房东都有一套房屋,您希望能够找到最昂贵的房屋和拥有它的房东。如果每个房屋都跟踪其房东和价格,并且每个房东都跟踪其房屋,那么应该可以使您将任何房屋链接到其房东,或者查看房东拥有的所有房屋。

以下模型可能会给您一个有关如何进行的想法。它创建了房东,然后每个房东都以随机价格创建房屋。然后,它找到最昂贵的房屋及其房东。然后,对于每个房东,它会找到房东最昂贵的房子。房东可以与[房东]一起保存房屋清单,但是第二项对于所有房东的房屋都是相同的。

breed [landlords landlord]
breed [houses house]

landlords-own [my-houses my-house-list]
houses-own [price my-landlord]

to test
  clear-all
  create-landlords 10
  ask landlords [
    hatch-houses 5 [
      set price precision (random-float 1) 3
      set my-landlord myself
    ]
    set my-houses houses with [my-landlord = myself]
  ]

  let most-expensive max-one-of houses [price]
  show (word "The mostexpensive house is house " most-expensive " owned by " [my-landlord] of most-expensive " with price =" [price] of most-expensive)

  ask landlords [
    let my-most-expensive max-one-of my-houses [price]
    show (word "landlord " self "'s most expensive house is house " most-expensive " with price =" [price] of my-most-expensive)
  ]
end

另一方面,您可以将所有房东的所有房屋清单作为全球清单保存,如果在测试后运行list-houses,您会得到这样的清单,然后可以按价格排序,房东或其他任何人。

globals [house-list]

to list-houses
  set house-list []
  ask houses [
    set house-list fput (list self my-landlord price) house-list
  ]
  show house-list
  let sorted-by-price sort-by [[a b] -> item 2 a > item 2 b] house-list
  let most-expensive first sorted-by-price
  show (word "the most expensive house is house " item 0 most-expensive " with owner " item 1 most-expensive " and price " item 2 most-expensive)
end