How to form subset form a set of numbers in Netlogo

224 views Asked by At

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

There are 1 answers

2
Seth Tisue On

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]]