Skip to content

Instantly share code, notes, and snippets.

@berkanaslan
Created June 4, 2022 11:08
Show Gist options
  • Save berkanaslan/2f51a15d57959a98079632e6399b106b to your computer and use it in GitHub Desktop.
Save berkanaslan/2f51a15d57959a98079632e6399b106b to your computer and use it in GitHub Desktop.
This is a recursive approach for permutation output.
package com.berkanaslan;
import java.util.Scanner;
public class RecursivePermutation {
public static void main(String[] args) {
final String input = getInput();
final String output = "";
permute(input, output);
System.out.println(output);
}
private static String getInput() {
final Scanner scanner = new Scanner(System.in);
System.out.println("Provide input: ");
return scanner.nextLine();
}
private static void permute(String input, String output) {
if (input.length() == 0) {
System.out.println(output);
return;
}
for (int i = 0; i < input.length(); i++) {
final char c = input.charAt(i);
final String leftCharsOfC = input.substring(0, i);
final String rightCharsOfC = input.substring(i + 1);
final String restOfTheInput = leftCharsOfC + rightCharsOfC;
permute(restOfTheInput, output + c);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment