How to select the item with highest value in a list

谁都会走 提交于 2020-01-25 08:58:05

问题


I have a list for each turtle I am considering in my model. I would like to select an item of a list, specifically, the item with highest quality. Quality is a parameter in the range [0,1]. My issues regards how to assign the parameter to each item, then select the item with the highest parameter value.

To better explain: an example of list is (item 4, item3, item2, item1). What I would like is: item 4 with quality #, item 3 with quality #, and so on. When I create the items of a list, they have a quality parameter (it's turtle-own): (quality random-float 1). Then, I should have something like this: item4 0.2, item3 1, item2 0.2, item1 0.5. What I would like to select is the item with highest quality, i.e. item3 with quality equal to 1.

To assign the parameter, I considered:

ask one-of turtles
     [
      ifelse empty? mylist
        [
          set quality random-float 1
          ...
        ]
     ]

I do not know if this is the right way to assign an attribute to an item of a list in Netlogo.

The steps for selecting an item are:

  1. Select a turtle
  2. Check that its list is not empty
  3. Select the item with highest quality of its list

Based on them, I would write as follows:

let mylist [ item4 item3 item2 item1 item0 item6] 
let max-value max mylist 
let max-index position max mylist 

The problem is that I am not sure that I am selecting the item with the highest quality, because I am not completely sure am assigning correctly the quality to an item.

I hope you can help me. Thanks


回答1:


Considering you have a structure that packs all the item proprieties together (ItemID, ItemName, ..., ItemValue) and an array of Items.

Item(ItemID, ItemName, ..., ItemValue) // these are the proprieties of our object Item
Item arr_items[NB_ITEMS] //  the array (list) of items you have

You can use the following algorithm, written in pseudo code, and transfer it to the language you use to pick the item with the highest value.

Pseudo code:

// Lets assume your array of items is called "arr_items"
// Lets also assume indexing start from 0
index_max  = 0 // first index
for i = 0 to length(arr_items) - 1: // loop though all items
    // if the current ith item have ItemValue bigger than index_max's items ItemValue 
    if arr_items[item_max].ItemValue > arr_items[i].ItemValue then 
        index_max = i // then change index_max to be i
return index_max  // return the index of the item with the highest value


来源:https://stackoverflow.com/questions/58582931/how-to-select-the-item-with-highest-value-in-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!