Home > Back-end >  How to get permutations of a string in Ruby without shifting order?
How to get permutations of a string in Ruby without shifting order?

Time:06-04

I'm trying to take a string, and return all possible permutations without shifting order. For example:

string_array = ["abc"]
empty_array = []
string_array.each do |element|
    for i in (0..(element.length-1)) do
        empty_array.push(element[0..i])
        i  = 1
    end
end

something like this would give ['a', 'ab', 'abc'].

However, I need ['a', 'ab', 'abc', 'b', 'bc', 'c'].

Is there anyway of modifying my code to include this?

CodePudding user response:

string_array.each do |element|
    for z in (0..element.length-1) do
        for i in (0..(element.length-1)) do
            empty_array.push(element[z..i])
            i  = 1
        end
    end
end

I solved this by nesting the for loop in another for loop, but if anyone else has a more efficient solution I would appreciate seeing it

CodePudding user response:

The idea for the following code is to repeat the process that gives you ['a', 'ab', 'abc'] from 'abc' for 'bc' and then 'c':

string_array = ["abc"]
empty_array = []
string_array.each do |element|
    for i in (0..(element.length-1)) do
        for j in (i..(element.length-1)) do
            empty_array.push(element[i..j])
        end
    end
end
  • Related