Generating permutations of a list in NetLogo

2020-02-13 01:34发布

I'm trying to generate a list in NetLogo that contains several different unique lists of numbers 0 through n. For example, I have this line of code

set mylists [[0 1 2] [0 2 1] [1 0 2] [1 2 0] [2 0 1] [2 1 0]]

that I wrote to make all possible unique combinations of 0 1 and 2 without any repetition of the numbers within the lists. I would like to be able to the same thing but with a larger n. Is there an example of how to do this, or some sort of pseudocode algorithm that anyone knows of that I could check out? Thanks!

1条回答
等我变得足够好
2楼-- · 2020-02-13 01:55

If you don't mind a recursive solution, you could do this:

to-report permutations [#lst] ;Return all permutations of `lst`
  let n length #lst
  if (n = 0) [report #lst]
  if (n = 1) [report (list #lst)]
  if (n = 2) [report (list #lst reverse #lst)]
  let result []
  let idxs n-values n [?]
  foreach idxs [
    let xi item ? #lst
    foreach (permutations remove-item ? #lst) [
      set result lput (fput xi ?) result
    ]
  ]
  report result
end

Edit: Updated syntax in response to comment.

to-report permutations [#lst] ;Return all permutations of `lst`
  let n length #lst
  if (n = 0) [report #lst]
  if (n = 1) [report (list #lst)]
  if (n = 2) [report (list #lst reverse #lst)]
  let result []
  let idxs range n
  foreach idxs [? ->
    let xi item ? #lst
    foreach (permutations remove-item ? #lst) [?? ->
      set result lput (fput xi ??) result
    ]
  ]
  report result
end
查看更多
登录 后发表回答