Skip to content

Instantly share code, notes, and snippets.

@jerrylususu
Created May 8, 2022 18:13
Show Gist options
  • Save jerrylususu/0d6c3dda0ea010d9af5ad0a996f9f5ee to your computer and use it in GitHub Desktop.
Save jerrylususu/0d6c3dda0ea010d9af5ad0a996f9f5ee to your computer and use it in GitHub Desktop.
Reimplement of Python's itertools.permutations in Java
public class PyItertoolPermutation {
public static void main(String[] args) {
char[] arr = {'A', 'B', 'C', 'D'};
int r = 2;
dfs(0, arr, r);
}
public static void dfs(int changing_idx, char[] arr, int r) {
if (changing_idx == r){
printFirstN(arr, r);
return;
}
// assume the input is already sorted
// initial trigger
dfs(changing_idx + 1, arr, r);
int remaining_choice = arr.length - 1 - changing_idx;
// tick
for (int i = 1; i <= remaining_choice; i++) {
int swap_idx = changing_idx + i;
swap(arr, changing_idx, swap_idx);
// trigger here
dfs(changing_idx + 1, arr, r);
}
// reset to keep the order
moveToLast(arr, changing_idx);
}
public static void swap(char[] arr, int i, int j){
char tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp;
}
public static void moveToLast(char[] arr, int idx) {
char tmp = arr[idx];
for (int i = idx; i < arr.length - 1; i++) {
arr[i] = arr[i+1];
}
arr[arr.length - 1] = tmp;
}
public static void printFirstN(char[] arr, int n){
for (int i = 0; i < n; i++) {
System.out.print(arr[i]);
}
System.out.println();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment