1

Here is my problem:

Given a multi dimensional array: [['monday', 'saturday'], ['beginner'], ['kid', 'adult']]

I want:

['monday', 'monday-beginner', 'monday-beginner-kid', 'monday-beginner-adult', 'monday-kid', 'monday-adult', 
 'saturday', 'saturday-beginner', 'saturday-beginner-kid', 'saturday-beginner-adult', 'saturday-kid', 'saturday-adult', 
 'beginner', 'beginner-kid', 'beginner-adult',
 'kid',
 'adult']

Here are questions I saw that could help:

7
  • The rule is not clear. Commented Dec 16, 2013 at 14:27
  • 3
    Why don't you want e.g. 'monday-kid' or 'saturday-adult'? In total you are missing 4 obvious combinations Commented Dec 16, 2013 at 14:27
  • 1
    And the trivial ''. Commented Dec 16, 2013 at 14:28
  • And how is permutation relevant here? It only looks like a combination problem. Commented Dec 16, 2013 at 14:31
  • 1
    To clarify sawa's commemt, a permutation might be 'kid-monday-beginner'. The difference is important for clarity, although that might be one of your sticking points of course - if you are not clear yourself on the difference between those terms, it is harder to approach the code correctly. Commented Dec 16, 2013 at 14:34

2 Answers 2

4
first, *rest = [['monday', 'saturday'], ['beginner'], ['kid', 'adult']]
.map{|a| [nil, *a]}
first.product(*rest).map{|a| a.compact.join("-")} - [""]
Sign up to request clarification or add additional context in comments.

1 Comment

Nice idea with mixed-in nil ;)
0

I've a solution in 2 steps : - Find all the possible combinaisons, 4 in your examples:

['monday', 'beginner', 'kid']
['monday', 'beginner', 'adult']
['saturday', 'beginner', 'kid']
['saturday', 'beginner', 'adult']

Then use combinaison method on it 3 times using n from 1 to 3 and then, merge the 3 returns. You'll finally just have to call .join("-") on each permutation.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.