AnswerBun.com

Java alternative of product function of python form itertools

Stack Overflow Asked by VIPUL TYAGI on November 8, 2020

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.

One Answer

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]

Answered by deadshot on November 8, 2020

Add your own answers!

Related Questions

Cannot append option for select form

1  Asked on November 20, 2021 by nguyn-v

   

Constructors with the same primitive type as parameter

3  Asked on November 18, 2021 by arjun-singh

   

Python regex for numbers between 0-63

3  Asked on November 18, 2021 by perplexityy

   

How can I retrieve many values of a same field in a GET request

2  Asked on November 18, 2021 by user2424634

       

Can i know why my while loop is not working?

0  Asked on November 18, 2021 by niranjan-kumar

 

Moment JS days difference issue

1  Asked on November 18, 2021

   

How to update the value of a prop upon a state change in React

2  Asked on November 18, 2021 by alopez02

 

reload div without refresh page

1  Asked on November 18, 2021 by kemar-aim

         

Convert heirachy to dict of lists

0  Asked on November 18, 2021 by himabindu

       

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir