0

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 ?

4
  • Do you know there is a predefined method permutation in Array class? Commented Apr 19, 2018 at 6:50
  • 1
    You don't have to write separate method for this. You simply write p arr.permutation.map{|s|s} that would do the job for you. Commented Apr 19, 2018 at 6:53
  • Hello @Rajagopalan, i knew that method, but for the big array, it will out of memory Commented Apr 19, 2018 at 6:56
  • Hi I have updated answer, you may have a look at that. Commented Apr 19, 2018 at 6:59

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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)

2 Comments

You'd probably be better off saying arr.permutation.to_a instead of the map{|s|s}. And the second one doesn't need any arrayification, just arr.permutation.take(4) would be sufficient.
@muistooshort Ah Okay! Thank you, updated the answer!

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.