Skip to content

Instantly share code, notes, and snippets.

@olokobayusuf
Last active June 8, 2017 21:25
Show Gist options
  • Save olokobayusuf/02fdffd770bedb900c68188639738637 to your computer and use it in GitHub Desktop.
Save olokobayusuf/02fdffd770bedb900c68188639738637 to your computer and use it in GitHub Desktop.
Permutations in Java
import java.util.Arrays;
import java.util.ArrayList;
public final class Permutations {
private static final int input[] = {1, 2, 3};
public static void main (String args[]) {
// Permute
ArrayList<int[]> permutations = permute(input);
// Print
for (int[] permutation : permutations) System.out.println(Arrays.toString(permutation));
}
private static ArrayList<int[]> permute (int[] numbers) {
// Create the result collection
ArrayList<int[]> result = new ArrayList<>();
// Permute
permute(result, new int[numbers.length], numbers, 0);
// Return it
return result;
}
private static void permute (ArrayList<int[]> result, int[] permutation, int[] numbers, int index) {
// Get the value at the index
int value = numbers[index];
// Loop
for (int i = 0; i < numbers.length; i++) {
// Check that we can place this value in the spot
if (permutation[i] != 0) continue;
// Place the value there
permutation[i] = value;
// Permute
if (index < numbers.length - 1) permute(result, permutation, numbers, index + 1);
// If we are at the last index, then we have a result
else result.add(permutation.clone());
// Reset the value
permutation[i] = 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment