Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create all combinations for items in an Array?

I did see this and this post on it, but it is not in Java or Kotlin, so it doesn’t help me. Now, coming to the problem, I want to be able to create all the possible combinations for an array. For example, I have this array:

[1,2,3,4]

And then all the possible combinations give us this:

[1,2,3,4]
[1,2,4,3]
[1,3,2,4]
[1,3,4,2]
[1,4,2,3]
[1,4,3,2]

[2,1,4,3]
[2,1,3,4]
[2,3,1,4]
[2,3,4,1]
[2,4,3,1]
[2,4,1,3]

[3,1,2,4]
[3,1,4,2]
[3,2,4,1]
[3,2,1,4]
[3,4,1,2]
[3,4,2,1]

[4,1,2,3]
[4,1,3,2]
[4,2,3,1]
[4,2,1,3]
[4,3,2,1]
[4,3,1,2]

I don’t want to have a space between these two different starts or numbers. I just added it for readability.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It should not only work for Integers but also for objects like strings, our classes, etc…

So, how can I achieve this in Java or Kotlin?


I also just came across this post, but it wanted for two arrays and needed for one. Also, it was closed, so I felt it better to ask another one.


Pls, don’t downvote. Just let me know what can be better.

>Solution :

If the task is not to implement the algorithm which generates the permutations you need, I would recomend to use a library like combinatoricslib3. If you happen to use Guava or Apache Commons in your projects, those have also some methods to generate combinations / permutations from a given collection. With combinatoricslib3 your code could look something like:

import org.paukov.combinatorics3.Generator;

public class Example {

    public static void main(String[] args) {
        Integer[] array = {1,2,3,4};
        Generator.permutation(array)
                .simple()
                .stream()
                .forEach(System.out::println);

        //Example with strings

        Generator.permutation("apple", "orange", "cherry")
                .simple()
                .stream()
                .forEach(System.out::println);
    }
}

output:

[1, 2, 3, 4]
[1, 2, 4, 3]
[1, 4, 2, 3]
[4, 1, 2, 3]
[4, 1, 3, 2]
....

and

[apple, orange, cherry]
[apple, cherry, orange]
[cherry, apple, orange]
[cherry, orange, apple]
[orange, cherry, apple]
[orange, apple, cherry]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading