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.
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]
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With