How to form subset form a set of numbers in Netlogo

放肆的年华 提交于 2019-12-11 09:40:06

问题


Dear Netlogo community,

I am looking to generate subset of a set of numbers. for example if a set is [1 2 3 4 5] then subset would be [1 2] [1 3] [1 4] [1 5] [ 1 2 3] [1 2 4]....... I know we can generate very easily by using bit manipulation in java. But I have no idea how to implement in Netlogo. I am doomed. Any help would be really appreciated. Thanks


回答1:


This is easiest to solve using recursion:

to-report subsets [xs]
  if empty? xs [ report [[]] ]
  let recurse subsets butfirst xs
  report sentence recurse
                  map [fput first xs ?] recurse
end

The basic idea is that if you want the subsets of [1 2 3], first you find all the subsets of [2 3]. All of them are themselves subsets of [1 2 3], plus if you stick the 1 on the front of each of them, the resulting lists are part of the answer too.

sample run:

observer> print subsets [1 2 3]
[[] [3] [2] [2 3] [1] [1 3] [1 2] [1 2 3]]


来源:https://stackoverflow.com/questions/30840493/how-to-form-subset-form-a-set-of-numbers-in-netlogo

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