英文:
Java alternative of product function of python form itertools
问题
在我的一个Java程序中,我需要使用itertools提供的product函数,对一个数组进行排列,重复k次。( perm=itertools.product(arr,repeat=k)
)。
例如,对于arr=[4,5]和k=3,输出应为:
(4, 4, 4)
(4, 4, 5)
(4, 5, 4)
(4, 5, 5)
(5, 4, 4)
(5, 4, 5)
(5, 5, 4)
(5, 5, 5)
我想问一下,在Java中是否有任何实用工具或类似的东西可以简化这个过程?我已经在互联网上寻找过,但无法在任何地方找到。
如果您知道在这种情况下应该如何操作,请分享一些相关信息。
英文:
In one of my java program, I need to use exactly what product function from itertools offers, permuting an array reapeating k times.( perm=itertools.product(arr,repeat=k)
).
for ex. for arr=[4,5] and k=3, the output should be:
(4, 4, 4)
(4, 4, 5)
(4, 5, 4)
(4, 5, 5)
(5, 4, 4)
(5, 4, 5)
(5, 5, 4)
(5, 5, 5)
I want to ask if there is any utility or something in java which can facilitate this in java? I have been looking for it over the internet, but couldn't find it anywhere.
Please share something if you know what could be done in this case.
答案1
得分: 3
尝试一下:
我已经使用了 Python 的 itertools.product 代码作为参考。
public class Util {
public static <T> List<Collection<T>> product(Collection<T> a, int r) {
List<Collection<T>> result = Collections.nCopies(1, Collections.emptyList());
for (Collection<T> pool : Collections.nCopies(r, new LinkedHashSet<>(a))) {
List<Collection<T>> temp = new ArrayList<>();
for (Collection<T> x : result) {
for (T y : pool) {
Collection<T> z = new ArrayList<>(x);
z.add(y);
temp.add(z);
}
}
result = temp;
}
return result;
}
public static void main(String[] args) {
product(List.of(4, 5), 3).forEach(System.out::println);
}
}
输出:
[4, 4, 4]
[4, 4, 5]
[4, 5, 4]
[4, 5, 5]
[5, 4, 4]
[5, 4, 5]
[5, 5, 4]
[5, 5, 5]
英文:
Try this:
I have used python itertools.product code as reference.
public class Util {
public static <T> List<Collection<T>> product(Collection<T> a, int r) {
List<Collection<T>> result = Collections.nCopies(1, Collections.emptyList());
for (Collection<T> pool : Collections.nCopies(r, new LinkedHashSet<>(a))) {
List<Collection<T>> temp = new ArrayList<>();
for (Collection<T> x : result) {
for (T y : pool) {
Collection<T> z = new ArrayList<>(x);
z.add(y);
temp.add(z);
}
}
result = temp;
}
return result;
}
public static void main(String[] args) {
product(List.of(4, 5), 3).forEach(System.out::println);
}
}
Output:
[4, 4, 4]
[4, 4, 5]
[4, 5, 4]
[4, 5, 5]
[5, 4, 4]
[5, 4, 5]
[5, 5, 4]
[5, 5, 5]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论