Generating permutations of a list in NetLogo

后端 未结 1 669
野的像风
野的像风 2020-12-19 23:52

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 myli         


        
相关标签:
1条回答
  • 2020-12-20 00:41

    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
    
    0 讨论(0)
提交回复
热议问题