Skip to content

Instantly share code, notes, and snippets.

@onepointconsulting
Created May 12, 2023 07:32
Show Gist options
  • Save onepointconsulting/18591d1904d1fd9cd637ff7c35624e70 to your computer and use it in GitHub Desktop.
Save onepointconsulting/18591d1904d1fd9cd637ff7c35624e70 to your computer and use it in GitHub Desktop.
package com.fernandes.exercises.util;
import static com.fernandes.exercises.util.Permutations.Mode.ALL;
import static com.fernandes.exercises.util.Permutations.Mode.ASC;
import java.util.ArrayList;
import java.util.List;
public class Permutations {
public enum Mode {
ALL,
ASC,
UNIQUE
}
private final Mode mode;
private final int targetDepth;
private final boolean addAll;
public Permutations(Mode mode, int depth) {
this.mode = mode;
this.targetDepth = depth;
this.addAll = false;
}
public Permutations(Mode mode, int depth, boolean addAll) {
this.mode = mode;
this.targetDepth = depth;
this.addAll = addAll;
}
public List<List<Integer>> permutate(int[] a) {
List<List<Integer>> acc = new ArrayList<>();
permutate(a, 0, 0, new ArrayList<>(), acc);
return acc;
}
public void permutate(int[] a, int start, int depth, List<Integer> previous, List<List<Integer>> acc) {
if (depth == a.length) {
return;
}
for (int i = start; i < a.length; i++) {
if (depth == targetDepth - 1) {
List<Integer> finalArray = new ArrayList<>(previous);
finalArray.add(a[i]);
acc.add(finalArray);
} else {
ArrayList<Integer> previous1 = new ArrayList<>(previous);
previous1.add(a[i]);
if (addAll) {
acc.add(previous1);
}
permutate(a, mode == ALL ? 0 : mode == ASC ? i : i + 1, depth + 1, previous1, acc);
}
}
}
}
@onepointconsulting
Copy link
Author

Simple Gist that you can use to permutate Java integer arrays.
Usage:

int[] a = {1, 2, 3};
List<List<Integer>> res = new Permutations(UNIQUE, a.length, true).permutate(a);
for (List<Integer> l : res) {
  System.out.println(l);
}

This prints:

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment