1
\$\begingroup\$

I was at the job interview yesterday. And there is a question that asks me to find all the permutations in an array of string in ruby:

input: ['abc', 'cba', 'ab', 'ba', 'acbdef']

output: ['abc', 'cba', 'ab', 'ba']

Here is my implementation:

def find_permutation(arr)
  result = []
  arr.each do |element|
    next if result.include?(element.reverse)
    if arr.include?(element.reverse)
      result << element << element.reverse
    end
  end
  result
end

I am wondering if there is a better way to solve the problem in ruby since I don't think my solution is really 'pure' ruby.

\$\endgroup\$
4
  • \$\begingroup\$ permutations are usually defined to be exactly as long as the permuted element.. your results include permuted substrings. I assume this is intentional? \$\endgroup\$
    – Vogel612
    Commented Jan 25, 2017 at 17:54
  • \$\begingroup\$ @Vogel612 Thank you for pointing it out. Yes, that is intentional because it is mentioned in the interview question. \$\endgroup\$
    – Fatima
    Commented Jan 25, 2017 at 17:59
  • \$\begingroup\$ Maybe you mean math.stackexchange.com/questions/tagged/combinatorics ? \$\endgroup\$ Commented Jan 25, 2017 at 18:03
  • \$\begingroup\$ Looking at the input/output, it doesn't seem like you're not really finding permutations, per se. It's rather that you filter the input to only include strings that appear "twice" in the input in opposite forms. So you're looking for one specific permutation (reverse), rather than finding all permutations of strings. \$\endgroup\$
    – Flambino
    Commented Jan 25, 2017 at 18:34

0

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.