Generate all subsets of a set

first-steps
optimization

#1

Hi, I’m very new in Julia, & I really need help to generate all subsets of a set.
For example: I have a set [1, 2, 3, 4, 5], then I need to generate all subsets from it, such [[1,2], [1,3], [2,3],…[2,3,4], …[2,3,4,5], etc]. Is there any suggestion about it?


#2

#3

Or if you’re bored:

cur_input_list = [1,2,3,4,5]

function foo(cur_input_list, cur_output_list=[], cur_set_lists=[])
  for (cur_index, cur_value) in enumerate(cur_input_list)
    tmp_input_list = cur_input_list[cur_index+1:end]
    tmp_output_list = deepcopy(cur_output_list)
    push!(tmp_output_list, cur_value)

    push!(cur_set_lists, tmp_output_list)
    foo(tmp_input_list, tmp_output_list, cur_set_lists)
  end

  cur_set_lists
end

foo(cur_input_list)

#4

Specifically, https://github.com/JuliaMath/Combinatorics.jl/blob/60a2343af0dfc54ab01af6bb2f21d0b5a51fb729/src/combinations.jl#L268-L280


#5

This is called the “powerset”. Google Julia powerset and you’ll get several results in addition to Combinatorics.jl.

Here is the Julia entry from rosettacode.org:

function powerset(x::Vector{T}) where T
    result = Vector{T}[[]]
    for elem in x, j in eachindex(result)
        push!(result, [result[j] ; elem])
    end
    result
end

#6

Thank you so much for all of your kindly helps! Really help me as a new beginner.