【问题标题】:Cartesian Product of an unbound number of arrays in Java [duplicate]Java中无限数量数组的笛卡尔积[重复]
【发布时间】:2016-05-28 06:02:20
【问题描述】:

假设您有一个未绑定的命名数组列表:

ArrayNode[] vertexes = new ArrayNode[] {
    new ArrayNode("nouns", new String[]{"John", "Mary"}),
    new ArrayNode("verbs", new String[]{"Eats", "Works", "Plays"}),
    new ArrayNode("objects", new String[]{"Food", "Computer", "Guitar"})
 };

给定一个要遵循的顺序,比如“nouns->verbs->objects”,我们可以使用什么算法来按照给定的顺序关联数组的所有元素?输出类似于以下内容:

["John Eats Food"], ["John Eats Computer"], ["John Eats Guitar"], 
["John Works Food"], ["John Works Computer"], ["John Works Guitar"], 
..., ..., ..., 
...,                 ["Mary Plays Computer"], ["Mary Plays Guitar"]

数组的数量是无限制的,对于给定的数组数量,序列可以是任意的。

解决方案

使用 Java 8 和 Google Guava 19 Lists.cartesianProduct 看看Iterative Cartesian Product in Java的答案

【问题讨论】:

  • 我正在尝试混合使用 DFS 和 BFS...不确定这是否是正确的方法...
  • 我正在寻找一个 Java 实现......但是,是的,你有参考一个简单的回溯示例吗?
  • Oriol 在评论中提供的链接有一些很好的实现,您可以将它们移植到 Java。尤其是this functional onethis recursive one
  • 我使用 Google Guava 的 List.cartesianProduct 方法实现。谢谢!

标签: java arrays algorithm depth-first-search breadth-first-search


【解决方案1】:

您可以以inorder 方式遍历数组,以获取所需顺序的输出。

【讨论】:

    猜你喜欢
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 2012-02-24
    • 2011-09-18
    • 2017-03-05
    相关资源
    最近更新 更多