-1

I have a list of 10 probabilities that I want to transform to line segments so I can perform roulette wheel selection. How can I transform to line segments?

Probability list: [0.17 0.15 0.14 0.14 0.11 0.1 0.06 0.06 0.04 0.03]

When transformed into line segments should be: [0.17 0.32 0.46 0.60 0.71 0.81 0.87 0.93 0.97 1.0]

Right now this is my code:

to calculate-s
let i 1 ;; previously added a 0 to list using set p-list fput 0 p-list
while [i < 11] [
  ask turtles [
    if [p] of self = item i p-list [
      let s (p + item (i - 1) p-list)
    ]
  ]
  set i (i + 1)
]
end

But of course it just sums the current probability and the previous one so I get: [0.17 0.32 0.29 0.28 etc]

Dan
  • 3
  • 3
  • 1
    Appears to be a duplicate of http://stackoverflow.com/questions/33570658/how-make-a-list-of-cumulative-sum-in-netlogo – Alan Feb 16 '17 at 01:15

1 Answers1

-1

I'm not sure exactly what you mean by line segments, but if you just want a self-contained block that creates a list where

newlist[i] = (oldlist[i] + (newlist[i - 1]))

You can use foreach to step through the old list and generate a new list of summed values, as below.

to make-segments

  let oldlist [0.17 0.15 0.14 0.14 0.11 0.1 0.06 0.06 0.04 0.03]
  let newlist []

  let n 0

  foreach oldlist [
    [x]->
    ifelse n < 1 [ ;;; if index is 0 you can't index 0 -1, so just use item 0
      set newlist lput item 0 oldlist newlist   
    ]
    [   ;;; else, add the item n from the old list to the 
        ;;; previous item in the new list.
      set newlist lput (precision (item n oldlist + item (n - 1) newlist) 2) newlist
    ]
    set n n + 1
  ] 

  print newlist

end
Luke C
  • 10,081
  • 1
  • 14
  • 21