python表单itertools产品函数的Java替代

2024-04-20 06:21:13 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的一个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中是否有任何实用程序或其他东西可以在java中实现这一点?我一直在网上找,但到处都找不到

如果你知道在这种情况下可以做什么,请分享一些东西


Tags: 函数程序实用程序情况数组javaproductrepeat
1条回答
网友
1楼 · 发布于 2024-04-20 06:21:13

试试这个:

我使用了pythonitertools.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]

相关问题 更多 >