1

I'm trying to push subsets into an array:

def subsets(arr)
    subsets = [[]]
    temp_arr = []
    i = 0
    while i < arr.length
        temp_arr << arr[i]
        subsets << temp_arr
        p subsets
        i+=1
    end
    return subsets
end

My results look like this:

[[], ["a"]]
[[], ["a", "b"], ["a", "b"]]
[[], ["a", "b", "c"], ["a", "b", "c"], ["a", "b", "c"]]

Why is it that every time I push the temp_array to the subset array, the previous result of pushing temp_array also changes?

Is there a way I can push the unique instances of temp_array and keep it in that state?

Also, can anyone give me a hint as to how I can get all subsets from an array?

2 Answers 2

2
subsets << temp_arr

temp_arr references to the actual Array object. After this, both the element appended to subsets and temp_arr reference to the same object.

If this is not what you expected, use dup to gets its copy:

subsets << temp_arr.dup
Sign up to request clarification or add additional context in comments.

Comments

1

The problem is you're pushing the same object, temp_arr, onto subsets.

Ruby generally does not copy data, it passes around references to objects. subsets << temp_arr puts a reference to temp_arr onto subsets, not whatever happens to be in temp_arr at the moment.

subsets[0] -> temp_arr
subsets[1] -> temp_arr
subsets[2] -> temp_arr

To avoid this, you want to make a copy of temp_arr and push that onto subsets.

while i < arr.length
    temp_arr << arr[i]
    subsets << temp_arr.clone
    p subsets
    i+=1
end

As an aside, your loop can be written better using each.

arr.each { |element|
    temp_arr << element
    subsets << temp_arr.clone
    p subsets
}

Or avoid the temp variable entirely by using an array slice.

arr.each_index { |idx|
    subsets << arr[0..idx]
    p subsets
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.