0

I have a program which prints the all the possibilities of permutations for a given string. But it is static, I hard coded 3 for loops, assuming that the string will be of length 3. But if I have to make it dynamic, the user may enter input a string of length 5. So what I'm asking is if I can inject for loops as per the input of the user?

import java.util.*;
import java.lang.*;

    class Ideone
    {
        public static void main (String[] args) throws java.lang.Exception
        {
            // your code goes here
            String input = "abc";
            int i=0,j=0,k=0;
            for(i=0;i<3;i++){
                for(j=0;j<3;j++){
                    for(k=0;k<3;k++){
                       System.out.println(input.charAt(i)+""+input.charAt(j)+""+input.charAt(k)); 
                    }
                }
            }       
        }
    }
gates
  • 4,465
  • 7
  • 32
  • 60
  • 2
    Recursion is normally used for such tasks e.g. http://stackoverflow.com/a/4240323/1413133 – Manos Nikolaidis Oct 20 '15 at 11:04
  • Is there any alternative than recursion, as I am not very well versed in it – gates Oct 20 '15 at 11:05
  • 4
    Recursion is one of those things that sounds scarier than it is - well worth playing with it until you are comfortable – CupawnTae Oct 20 '15 at 11:06
  • By the way, are you sure that's what you want to do? At the moment you are using the length of the string for two different purposes - one is to loop through all the letters for each position, and one is to determine the number of positions. Those two aren't necessarily the same. E.g. you could have four loops with "abc" and have "aaaa", "aaab", "aaac", "aaba" etc. Or were you aiming for no repetition, i.e. "abc", "acb", but not "aaa" (in which case you have other problems)? – CupawnTae Oct 20 '15 at 13:37
  • Yes, the output from the above code is what I wanted. That is the repetition as you mentioned aaa, aba, aac like that. But I have do it dynamically, I look forward to implement the recursive solution. – gates Oct 20 '15 at 15:12

1 Answers1

0

Nope, injecting for loops isn't something that's feasible (fortunately, it would make the language a mess!)

Tasks like this would usually be achieved using recursion, which can easily be used to generate permutations (of strings, arrays or anything else.)

If you really don't want to use recursion there are other ways around it, you can calculate permutations via rotation in loops for instance - but these approaches will generally be harder to follow (and write.)

Michael Berry
  • 70,193
  • 21
  • 157
  • 216