【问题标题】:Recursive solution to permutation置换的递归解
【发布时间】:2012-01-27 12:38:21
【问题描述】:

我有一个如下所示的数据结构:

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

我希望这是递归的,但我已经研究了一个小时,我想要另一双眼睛。我在这里错过了什么?

【问题讨论】:

  • 你的数据结构错误。 "wor"{:choices=>["ld", "d"]}"there" 这三个元素将被解释为替代,因此不会给出您想要的结果。

标签: ruby algorithm data-structures recursion


【解决方案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"]

【讨论】:

  • 您完全正确地认为我的版本中的数据结构不正确。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-09
  • 2013-11-25
  • 1970-01-01
  • 2019-10-18
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
相关资源
最近更新 更多