robbywh
robbywh

Reputation: 323

pushing array to array in ruby have a wrong result

I have problem when pushing array to array, the result is not as I expected.

I run this code below :

 @arr = ["e", "s", "l", "e"]

    def permutations(array, i=0)
      combined_array = Array.new
      (i..array.size-1).each do |j|
        array[i], array[j] = array[j], array[i]
        puts "ARRAY : #{array}"
        combined_array << array.to_a
      end
      return combined_array
    end

permutations(@arr)

I got the output :

ARRAY : ["e", "s", "l", "e"]
ARRAY : ["s", "e", "l", "e"]
ARRAY : ["l", "e", "s", "e"]
ARRAY : ["e", "e", "s", "l"]
=> [["e", "e", "s", "l"], ["e", "e", "s", "l"], ["e", "e", "s", "l"], ["e", "e", "s", "l"]] 

Result expected :

ARRAY : ["e", "s", "l", "e"]
ARRAY : ["s", "e", "l", "e"]
ARRAY : ["l", "e", "s", "e"]
ARRAY : ["e", "e", "s", "l"]
=> [["e", "s", "l", "e"], ["s", "e", "l", "e"], ["l", "e", "s", "e"], ["e", "e", "s", "l"]] 

How to solve this problem ?

Upvotes: 0

Views: 45

Answers (2)

Rajagopalan
Rajagopalan

Reputation: 6064

I think @GolfWolf has solved your problem.

But you don't have to write such a function to solve your problem in Ruby, Ruby has permutation method which you can use it.

p arr.permutation.to_a

If you want to get first 4 element then you can do this,

p arr.permutation.take(4)

Upvotes: 1

Cristian Lupascu
Cristian Lupascu

Reputation: 40516

According to the documentation, #to_a called on an Array returns self (the array itself, not a copy).

You are adding the same array to combined_array multiple times.

Change the .to_a to .dup and it will work fine.

Upvotes: 2

Related Questions