سؤال

I have a long string in which each character has a specified number of options. For a shorter example, lets say I have a 4 character string. The first character can be a number 1-6, the second character can be 1-5 or a-e, the third character can only be a or b, and the fourth character can be 0-9 or a-z. How can I pragmatically generate a list or array of all possible permutations of my string using Ruby (RoR)? A space can also be used for any of the characters.

So an example of the string could be:

1aaz
21b0
21 0
1 a1
هل كانت مفيدة؟

المحلول

Here's a simple solution:

strform = [%w(1 2 3 4 5 6), %w(1 2 3 4 5 a b c d e), %w(a b), %w(0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z)]
strform[0].product(*strform[1..-1]).map(&:join)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top