1

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,

MoMo
  • 321
  • 2
  • 3
  • 8
  • 2
    NB: all lists are of the same length, and I cannot use the table or array extensions – MoMo May 18 '18 at 11:13

2 Answers2

2

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.

Nicolas Payette
  • 14,847
  • 1
  • 27
  • 37
1

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
MoMo
  • 321
  • 2
  • 3
  • 8