MoMo
MoMo

Reputation: 331

NetLogo: How to compare two sublists

I am not from a computer science background and I am also new to NetLogo, so I would really appreciate your help. My question is as follows:

Let assume that I have a list of three lists

Let mylist [ [ 1 2 3 4 5 ] [ 2 2 2 2 2 ] [ 3 3 3 3 3 ] ]

I would like to check each item within item 2 mylist (i.e. [ 3 3 3 3 3 ]) and see if it is not equal to the corresponding item in item 0 mylist (i.e. [ 1 2 3 4 5 ]). If that the case, I would like to subtract a constant value which is 5 from that item in item 2 mylist.

In other words, I would like mylist to be changed to the following:

[ [ 1 2 3 4 5 ] [ 2 2 2 2 2 ] [ -2 -2 3 -2 -2 ] ]

Thanks in advance,

Upvotes: 1

Views: 303

Answers (2)

Nicolas Payette
Nicolas Payette

Reputation: 14972

Your own answer is fine, but here is what I consider to be a somewhat more elegant way to do it:

print lput (map [ [ a b ] ->
  ifelse-value (a = b) [ b ] [ b - 5 ]
] (item 0 mylist) (item 2 mylist)) but-last mylist

The key primitive here is map, which is to foreach what of is to ask: instead of running a command on each element, it runs a reporter and builds a new list out of the results. In this particular case, it saves you from having to mess with indices and replace-item inside.

The combination of lput and but-last makes it easy to replace the last sublist in your main list, but you could also use replace-item for that. Or, depending on what you need it for, you could just use the result of map directly instead of putting it back in your main list.

Upvotes: 2

MoMo
MoMo

Reputation: 331

I managed to solve the problem by separating the sublists:

to go
Let mylist [ [ 1 2 3 4 5 ] [ 2 2 2 2 2 ] [ 3 3 3 3 3 ] ]
let auxiliar-list1 item 0 mylist
let auxiliar-list2 item 2 mylist
foreach ( range 0 ( length auxiliar-list1 ) ) [ num-item ->
    if item num-item auxiliar-list1 != item num-item auxiliar-list2 [
      set auxiliar-list2 replace-item num-item auxiliar-list2 (item num-item auxiliar-list2 - 5)
      show mylist
      show auxiliar-list1
      show auxiliar-list2
    ]
 ]  
end

Upvotes: 1

Related Questions