1

I have an array of strings "A" and a target string "B". The B string contains only characters from a to z and does not contain spaces. I need a ruby function that returns the array of strings which represents all possible ways to form B from elements of Array A. The order in which combinations are returned is irrelevant. Words from A can be used multiple times.

Example:

A = [‘x’, ‘y’, ‘z’, 'yz',‘xy’, ‘xyz’] 

B = ‘xyz’ 

method(A, B) => [x y z, x yz, xyz, xy z]  

I looked into permutation method but can't get it to work.

2
  • Could you provide an example of what've tried so far, and if possible an example of what the output should look like? Commented Oct 3, 2013 at 21:38
  • A = [‘x’, ‘y’, ‘z’, ‘yy’, ‘yz’] B = ‘xyyz’ method_name(A, B) => [‘x y yz’, ‘xy yz’, etc] Ive tried scanning and mapping - so frustrating! Im new to Ruby and I always have such a hard time. Commented Oct 3, 2013 at 21:55

2 Answers 2

1

Here's a recursive solution that doesn't iterate through the permutations:

def find_possible_combinations( list, str )
  list.select { |a| str.start_with? a }.map do |a|
    if a == str
      [a]
    else
      find_possible_combinations( list-[a], str.slice(a.length..-1) )
        .map { |c| "#{a} #{c}" }
    end
  end.flatten
end

puts "#{find_possible_combinations( %w( x y z yz xy xyz ), 'xyz' )}"

Output:

["x y z", "x yz", "xy z", "xyz"]
Sign up to request clarification or add additional context in comments.

Comments

0
A = %w[x y z yz xy xyz] 
B = "xyz"
SIZE = B.size

def combos
  (1..SIZE).inject([]) {|c, n| c.concat(combos_by_size(n))}.reject(&:empty?)
end

# Select all combinations of size n having SIZE characters
def combos_by_size(n)
  A.combination(n).to_a.inject([]) {|c, a| c.concat(matching_combos(a)) if a.join.size == SIZE; c}.reject(&:empty?)
end


# Select all matching combinations using all elements of array a
def matching_combos(a)
  a.permutation.to_a.select {|p| p.join == B}
end

combos # => [["xyz"], ["x", "yz"], ["xy", "z"], ["x", "y", "z"]]

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.