ruby - 置换的递归解

标签 ruby algorithm data-structures recursion

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

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

关于ruby - 置换的递归解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8628136/

相关文章:

data-structures - Clojure 中 2D 游戏板的适当表示

ruby-on-rails - 使用 Ruby 查询具有多个值的哈希数组

mysql - Mac Os rake 数据库 :create through error with qt and mysql dependence

ruby - 为什么要在 Ruby 方法名称前加上 self?

algorithm - 将数组拆分为具有相似权重的子数组

c++ - 如何迭代 boost::mutable_queue

ruby-on-rails - 安装eventmachine(1.0.3)时出错,Bundler无法继续

algorithm - 处理评级系统的最佳方式

java - "Perfect"碰撞检测算法修复

python defaultdict 如何在不创建 key 的情况下检查嵌套 key 是否存在或是否为 []