Generating permutations of a list in NetLogo

会有一股神秘感。 提交于 2019-12-18 06:59:36

问题


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:


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


来源:https://stackoverflow.com/questions/33815666/generating-permutations-of-a-list-in-netlogo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!