2011-12-25 85 views
2

我有一个数据结构,它看起来像这样:递归地解决置换

[ 
    {:choices=>["Hello", "Hi"]}, 
    " ", 
    {:choices=>["wor", {:choices=>["ld", "d"]}, "there"]}, 
    ", says ", 
    "your ", 
    {:choices=>["friend", "amigo"]} 
] 

在这种结构中,选择节点表示的一组可能值的和可以由。

我需要一个(可能是递归的)Ruby方法,它将输出所有可能输出的数组。即,在这个例子:

[ 
    "Hello word, says your friend", 
    "Hello world, says your friend", 
    "Hello there, says your friend", 
    "Hi word, says your friend", 
    "Hi world, says your friend", 
    "Hi there, says your friend", 
    "Hello word, says your amigo", 
    "Hello world, says your amigo", 
    "Hello there, says your amigo", 
    "Hi word, says your amigo", 
    "Hi world, says your amigo", 
    "Hi there, says your amigo" 
] 

我希望这是递归的,但我一直在敲打它我的头一个小时,我想多了一双眼睛。我在这里错过了什么?

+0

你的数据结构是错误的。 “wor”,'{:choices => [“ld”,“d”]}','“there”三个元素将被解释为替代,因此不会给出您想要的结果。 – sawa 2011-12-25 04:52:17

回答

1

让原始数据是a,我想你想的是:

def expand s, x = nil, *a 
    case x 
    when Hash then x[:choices].each{|x| expand(s, x, *a)} 
    when Array then expand(s, *x, *a) 
    when String then expand(s+x, *a) 
    when nil then @combination << s 
    end 
end 

@combination = [] 
expand("", a) 
@combination # => result 

但是,你给的数据是错误的。它不会给你想要的东西:

a = [ 
    {:choices=>["Hello", "Hi"]}, 
    " ", 
    {:choices=>["wor", {:choices=>["ld", "d"]}, "there"]}, 
    ", says ", 
    "your ", 
    {:choices=>["friend", "amigo"]} 
] 

@combination = [] 
expand("", a) 
@combination # => 
["Hello wor, says your friend", 
"Hello wor, says your amigo", 
"Hello ld, says your friend", 
"Hello ld, says your amigo", 
"Hello d, says your friend", 
"Hello d, says your amigo", 
"Hello there, says your friend", 
"Hello there, says your amigo", 
"Hi wor, says your friend", 
"Hi wor, says your amigo", 
"Hi ld, says your friend", 
"Hi ld, says your amigo", 
"Hi d, says your friend", 
"Hi d, says your amigo", 
"Hi there, says your friend", 
"Hi there, says your amigo"] 

如果将其更改为

a = [ 
    {:choices=>["Hello", "Hi"]}, 
    " ", 
    {:choices=>[[ 
     "wor", 
     {:choices=>["ld", "d"]} 
    ], "there"]}, 
    ", says ", 
    "your ", 
    {:choices=>["friend", "amigo"]} 
] 

那么你将得到:

@combination = [] 
expand("", a) 
@combination # => 
["Hello world, says your friend", 
"Hello world, says your amigo", 
"Hello word, says your friend", 
"Hello word, says your amigo", 
"Hello there, says your friend", 
"Hello there, says your amigo", 
"Hi world, says your friend", 
"Hi world, says your amigo", 
"Hi word, says your friend", 
"Hi word, says your amigo", 
"Hi there, says your friend", 
"Hi there, says your amigo"] 
+0

而且我的版本中的数据结构不正确,你完全正确。 – Andrew 2011-12-26 04:51:17