gpt4 book ai didi

java - 在 Java 中查找可变数量的字符串数组的乘积

转载 作者:行者123 更新时间:2023-11-30 11:57:33 24 4
gpt4 key购买 nike

是否有与 Ruby 的 Array#product 方法等效的 Java 方法,或者这样做的方法:

groups = [
%w[hello goodbye],
%w[world everyone],
%w[here there]
]

combinations = groups.first.product(*groups.drop(1))

p combinations
# [
# ["hello", "world", "here"],
# ["hello", "world", "there"],
# ["hello", "everyone", "here"],
# ["hello", "everyone", "there"],
# ["goodbye", "world", "here"],
# ["goodbye", "world", "there"],
# ["goodbye", "everyone", "here"],
# etc.

这个问题是这个问题的 Java 版本:Finding the product of a variable number of Ruby arrays

最佳答案

这是一个利用递归的解决方案。不确定你想要什么输出,所以我刚刚打印了产品。您还应该查看 this问题。

public void printArrayProduct() {
String[][] groups = new String[][]{
{"Hello", "Goodbye"},
{"World", "Everyone"},
{"Here", "There"}
};
subProduct("", groups, 0);
}

private void subProduct(String partProduct, String[][] groups, int down) {
for (int across=0; across < groups[down].length; across++)
{
if (down==groups.length-1) //bottom of the array list
{
System.out.println(partProduct + " " + groups[down][across]);
}
else
{
subProduct(partProduct + " " + groups[down][across], groups, down + 1);
}
}
}

关于java - 在 Java 中查找可变数量的字符串数组的乘积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3743076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com