Created
June 4, 2022 11:08
-
-
Save berkanaslan/2f51a15d57959a98079632e6399b106b to your computer and use it in GitHub Desktop.
This is a recursive approach for permutation output.
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.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