2011-12-25 84 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