Reputation: 67
I want to create a list out of its own values for a given length.
For example, given the list [0 1]
and a desired list length of 7, the output would be [0 1 0 1 0 1 0]
. The length is defined by population
, and is defined by a slider. I declared the variable x
that should iterate through the list. If the length of the list is shorter than the value of population
it should be set to 0
again.
I tried it with a loop command but it runs infinitely:
let x 0
loop[
if length exp-dif-li <= population[
ifelse x < length exp-dif-li[
set x 0]
[ set exp-dif-li lput item x exp-dif-li exp-dif-li
set x x + 1]
]
]
]
Upvotes: 4
Views: 824
Reputation: 12580
mod
and n-values
are your friends here:
to-report continue-list [ lst n ]
report n-values n [ item (? mod length lst) lst ]
end
Example uses:
observer> show continue-list [0 1] 7
observer: [0 1 0 1 0 1 0]
observer> show continue-list [0 1] 1
observer: [0]
observer> show continue-list [0 1 2 3 4] 22
observer: [0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1]
Edit: Realized it would be good to talk about why this works! n-values n [ ... ]
creates a list of length n
by sending the numbers 0
through n - 1
to the given reporter. The reporter accesses the number with ?
(this is the NetLogo task syntax). So we want to keep repeating the items in the original list. A really good function for repeatedly cycling through numbers is mod
. In general, item i
of the new list should be item i mod <length of original list>
. So, putting that together, n-values n [ item (? mod length lst) lst ]
creates a new list of length n
by repeating the items from the list lst
as necessary.
Upvotes: 5
Reputation: 2096
To get out of a loop you need to call end or stop.
inserting the line
if length exp-dif-li = 7 [stop]
the right place would do it. Loop can very easily turn into a infinite loop and a freeze so it is best avoided.
I prefer while loops. they are safer and less prone to infinite loops which would look like this
while length exp-dif-li < 7
[
if length exp-dif-li <= population[
ifelse x < length exp-dif-li[
set x 0]
[ set exp-dif-li lput item x exp-dif-li exp-dif-li
set x x + 1]
]
Netlogo has another method which I have not seen elsewhere and is very robust against infinite loops. [repeat] the usage in you case would seem to be
repeat 7 [
if length exp-dif-li <= population[
ifelse x < length exp-dif-li[set x 0]
[ set exp-dif-li lput item x exp-dif-li exp-dif-li
set x x + 1]
]
Upvotes: 1