簡體   English   中英

排列的遞歸解

[英]Recursive solution to permutation

我有一個看起來像這樣的數據結構:

[
  {: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"
]

我希望這是遞歸的,但是我已經將頭撞了一個小時,我想要另一雙眼睛。 我在這里想念什么?

讓原始數據是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"]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM