Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java alternative of product function of python form itertools

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.

like image 675
Vipul Tyagi Avatar asked Sep 19 '25 22:09

Vipul Tyagi


1 Answers

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]
like image 109
deadshot Avatar answered Sep 22 '25 12:09

deadshot