-1
public class Main {

public static void main(String[] args) {
permutationWithRepeation("PQR");

 }

private static void permutationWithRepeation(String str1) {
System.out.println("The given string is: PQR");
System.out.println("The permuted strings are:");
showPermutation(str1, "");
 }
private static void showPermutation(String str1, String NewStringToPrint) {

if (NewStringToPrint.length() == str1.length()) {
   System.out.println(NewStringToPrint);
   return;
  }
  for (int i = 0; i < str1.length(); i++) {

   showPermutation(str1, NewStringToPrint + str1.charAt(i));
  }
 }
}

I am not able to understand after PPP The output of the code is The given string is: PQR The permuted strings are: PPP PPQ PPR PQP PQQ PQR PRP PRQ PRR QPP QPQ QPR QQP QQQ QQR QRP QRQ QRR RPP RPQ RPR RQP RQQ RQR RRP RRQ RRR

hashim
  • 9
  • 1
  • You may want to set a breakpoint on the println statement and look at the call stack. You will see that there are several calls each having their own value of I. – Thorbjørn Ravn Andersen May 22 '21 at 05:57
  • 1
    Adding nonsense-text to your question to circumvent the automated quality check is not a good idea. --- Please read: [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Turing85 May 22 '21 at 05:59

1 Answers1

2

The main idea is recursion. On each recursion level you put character at next position. Loop at each level is used to put all possible characters at next position and to go into next recursion level. When all characters are set your string has length 3 and recursion stops.

Sergey Afinogenov
  • 2,137
  • 4
  • 13