Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all subsets in an array

I need help with solving this ruby array question.

Get all the subsets of an array. Unique set only. No repeats of any number. num_subset([1,2,3]) ==> result should be [[], ["1"], ["1", "2"], ["1", "2", "3"], ["1", "3"], ["2"], ["2", "3"], ["3"]]

def num_subset(arr)
    holder =[]
    order_subset = [[]]

    (arr.length).times do |m|  
        arr.map do |n|
            holder += [n]  
            order_subset << holder
        end
    holder =[]  # resets holder
    arr.shift  # takes the first element out
    end
    order_subset
end

My result ==> [[], ["1"], ["1", "2"], ["1", "2", "3"], ["2"], ["2", "3"], ["3"]. My problem is that I am missing one result ["1", "3"]

Need some help pointing me to the right direction. Spent hours on this already. Do not use #combination short cut. I need to work this out manually.

like image 402
hken27 Avatar asked Dec 20 '22 21:12

hken27


1 Answers

a = [1, 2, 3]
arr = []

for i in 0..(a.length) do
  arr = arr + a.combination(i).to_a
end

> arr
# [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
like image 111
Santhosh Avatar answered Jan 08 '23 01:01

Santhosh