Search code examples
listiterationnetlogodistanceoperation

Iterate over a list of distances in Netlogo


I need help for the following issue. Basically, I have four turtles and a list of distances among them, let's say [ 0 1 2 3 ]. Zero is the distance of a turtle from itself. I want to obtein the following list [ 0, 1/5, 2/4, 3/3 ]. In other terms, I want to divide each number to the sum of all the other numbers. Can you help me?


Solution

  • The map primitive allows you to make a calculation for each item in a list separately and returns a new list of the results, as shown by the following examples from the Netlogo dictionary:

    show map round [1.1 2.2 2.7]
    => [1 2 3]
    show map [ i -> i * i ] [1 2 3]
    => [1 4 9]
    

    Now applying this to your case, I let every item of the list be divided by the sum of all items in the list minus its own value:

    to test
      
      let the-list [ 0 1 2 3 ]
      let total sum the-list
      let new-list map [ x -> x / (total - x)] the-list
      
      show new-list
      ;=> [0 0.2 0.5 1]
    
    end