Created
May 12, 2023 07:32
-
-
Save onepointconsulting/18591d1904d1fd9cd637ff7c35624e70 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simple Gist that you can use to permutate Java integer arrays.
Usage:
This prints: