Home > Software engineering >  Combination of a list of objects
Combination of a list of objects

Time:05-12

I have a problem that I can't solve. I hope I can make you understand it.

Given the following list of Waypoint objects

List<Waypoint>myWaypoint = new ArrayList<Waypoint>();

I want to calculate the combinations no repetition of groups of 3 (k=3) of the elements in the list and and create a matrix containing only k-group combinations

Example:

List<Waypoint>myWaypoint = new ArrayList<Waypoint>();

Waypoint a = new Waypoint();
Waypoint b = new Waypoint();
Waypoint c = new Waypoint();
Waypoint d = new Waypoint();



myWaypoint.add(a);
myWaypoint.add(b);
myWaypoint.add(c);
myWaypoint.add(d);
  • n!/(r!(n-r)!)

    k = 3 n = 4 -> combination: 4

New array of Waypoint object

Expected result of the matrix

The goal is to generate an array containing these objects

CodePudding user response:

If implementing the algorithm is not part of the task, I would recomend a library like combinatoricslib3 which will generate the combinations for you.

Using combinatoricslib3 a simple example using Strings:

Generator.combination("A", "B", "C", "D")
        .simple(3)
        .stream()
        .forEach(System.out::println);

will give you an output

[A, B, C]
[A, B, D]
[A, C, D]
[B, C, D]

You can use the lib to generate combinations of your custom objects by just passing your list and for example collect them to a list of lists. Below an example as a starting point:

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.paukov.combinatorics3.Generator;

public class Example {

    public static void main(String[] args) {
        List<Waypoint> myWaypoint = new ArrayList<>();
        Waypoint a = new Waypoint("a");
        Waypoint b = new Waypoint("b");
        Waypoint c = new Waypoint("c");
        Waypoint d = new Waypoint("d");
        myWaypoint.add(a);
        myWaypoint.add(b);
        myWaypoint.add(c);
        myWaypoint.add(d);

        List<List<Waypoint>> combinations = Generator.combination(myWaypoint)
                .simple(3)
                .stream()
                .collect(Collectors.toList());

        combinations.forEach(System.out::println);
    }

    static class Waypoint {
        String name;
        public Waypoint(String name) {
            this.name = name;
        }
        @Override
        public String toString() {
            return name;
        }
    }
}

You might want to read this post java-combinations-algorithm to find alternatives like Apache Commons or Google Guava

  • Related