Set of functions using Function interface

262 Views Asked by At

Let there be a set A = {1,2,3}. The goal is to compute all bijections on AxA. It should be of type Set<Function<T,T>> so that in the driver code, we can use the "apply" function.

I have tried a lot and have also figured out that the bijections will be the permutations of set A and have also computed that, but I'm unable to write code to create a Set of Functions(Mappings) for this.

It's a homework assignment, so any hint would be appreciated. Also, we have to use Java 8 functional programming features.

1

There are 1 best solutions below

0
AudioBubble On

Try this.

public static <T> Set<Function<T, T>> bijectionsOf(Set<T> set) {
    ArrayList<T> domain = new ArrayList<>(set);
    return permutations(domain, new ArrayList<>(), set.size(), 0)
        .stream()
        .map(list -> (Function<T, T>) t -> list.get(domain.indexOf(t)))
        .collect(Collectors.toSet());
}

output:

1 --> 1; 2 --> 3; 3 --> 2;
1 --> 3; 2 --> 2; 3 --> 1;
1 --> 2; 2 --> 1; 3 --> 3;
1 --> 3; 2 --> 1; 3 --> 2;
1 --> 1; 2 --> 2; 3 --> 3;
1 --> 2; 2 --> 3; 3 --> 1;