Question

replacing in nested list ??

for example

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

to

[[99 2][3 4] [5 1]]

Can anybody please clarify the use of lists in Netlogo?

Was it helpful?

Solution

Your question is somewhat underspecified. How do you want to decide which item gets changed?

I'll suppose that you want to do it by indices, e.g. "0th item of 0th sublist". Then that's:

to-report replace-subitem [index1 index2 lists value]
  let old-sublist item index1 lists
  report replace-item index1 lists (replace-item index2 old-sublist value)
end

observer> show replace-subitem 0 0 [[1 2] [3 4] [5 1]] 99
observer: [[99 2] [3 4] [5 1]]

You could also imagine doing the replacement according to other criteria. For example, suppose we want to change all of the occurrences of 1 in the first item of a sublist to 99. Then that's:

to-report replace-first [old new the-list]
  if first the-list = old
    [ report replace-item 0 the-list new ]
  report the-list
end

to-report replace-firsts [old new lists]
  report map [replace-first old new ?] lists
end

observer> show replace-firsts 1 99 [[1 2] [3 4] [1 1]]
observer: [[99 2] [3 4] [99 1]]

A lot of other answers are possible as well, depending on exactly what problem you're trying to solve.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top