如何生成字符串中指定字符替换为多字符的所有可能组合?
Hey there! Let's figure out how to generate all possible string combinations based on your character replacement rules. I'll walk you through a straightforward Ruby solution that fits your needs perfectly.
Problem Breakdown
First, let's clarify the replacement rules you laid out:
- Original character
acan be swapped with:1, $, A, @ - Original character
bonly has one replacement:B - Original character
chas these options:#, 0, 07, cd, CD, Cd, cD, dd, DD - Original character
whas a longer list of replacements:n, NN, l, L, !, 1, ), (, 0, #, &, %, $, ^, ##, ^^ - Characters
dandxstay exactly as they are (since no replacement options were provided for them)
Ruby Solution
Here's a clean implementation that generates every valid combination:
# Set up our base string and replacement rules as a hash base_string = "abcdwx" replacements = { 'a' => ['1', '$', 'A', '@'], 'b' => ['B'], 'c' => ['#', '0', '07', 'cd', 'CD', 'Cd', 'cD', 'dd', 'DD'], 'w' => ['n', 'NN', 'l', 'L', '!', '1', ')', '(', '0', '#', '&', '%', '$', '^', '##', '^^'] } # Split the base string into individual characters char_list = base_string.chars # For each character, get its possible values (use the original if no replacements exist) possible_options = char_list.map { |char| replacements.fetch(char, [char]) } # Generate all possible combinations using Cartesian product, then join into full strings all_combinations = possible_options[0].product(*possible_options[1..]).map(&:join) # Quick check: Print a few random valid combinations puts "Sample valid combinations:" 3.times { puts all_combinations.sample }
How This Code Works
Let's break down the key parts so you understand what's happening:
- Replacement Hash: We use a hash to map each character to its list of allowed replacements. For characters without replacements (like
dandx), we default to an array containing just the original character. - Possible Options Array: We convert the base string into an array of characters, then replace each character with its list of possible values. This gives us an array of arrays, where each sub-array holds all choices for that position in the string.
- Cartesian Product: Ruby's
productmethod is ideal here—it takes multiple arrays and returns every possible combination of one element from each array. We then join each combination tuple into a complete string. - Verification: The sample output will show you random valid combinations, and your examples (
1bcd##x,abDDd!x,aBcDdNNx) will all be present in theall_combinationsarray.
Quick Note on Combination Count
Just for context, let's calculate how many total combinations this will generate:
4 (options for a) × 1 (options for b) × 9 (options for c) × 16 (options for w) × 1 × 1 = 576 total combinations. That's a manageable number for Ruby to handle quickly.
内容的提问来源于stack exchange,提问作者JordanS
相关产品推荐
相关产品推荐

