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.
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With