Sikander
Sikander

Reputation: 2835

String permutation using for loops

I have to print all the possible permutations of the given input string.

Using the code below I get aaaa bbb ccc now in next iteration I want to print aaa aab aac. aba aca and so on. Please guide me about it.

String s = "abc";
char ch;
ArrayList<Character> input = new ArrayList<Character>();

public static void main (String [] args)
{
  String  s= "abc";
  int count ; 
  char ch;
  ArrayList<Character> input = new ArrayList<Character>();
  for (int i=0; i < s.length(); i++)
  {
    ch = s.charAt(i);
    input.add(ch);         
  }       


  for (int i=0; i <= input.size(); i++)
  {
    for(int j=0; j < input.size(); j++)
    {
      System.out.print(input.get(i));
    } 
    System.out.println();
  } 
}

Upvotes: 1

Views: 7293

Answers (3)

StreakyCobra
StreakyCobra

Reputation: 2001

A recursive version which is not dependent of the number of characters:

class Test
{
    public static void main(String[] args)
    {
        if(args.length != 1)
        {
            System.out.println("Usage: java Test <string>");
            System.exit(1);
        }

        String input = args[0];

        iterate(input, "", input.length());
    }

    public static void iterate(String input, String current, int level)
    {
        if(level == 0)
        {
            System.out.println(current);
            return;
        }

        for(int i=0; i < input.length(); i++)
        {
            iterate(input, current + input.charAt(i), level-1);
        }
    }

Upvotes: 2

Spinning
Spinning

Reputation: 79

You can use recursive function. Example

private static String text = "abcd";

public static void main(String[] args) {
    loopPattern(text, 0, "");
}

private static void loopPattern(String source, int index, String res) {
    if (source == null || source.length() == 0) {
    return;
    }
    if (index == source.length()) {
        System.out.println(res);
        return;
    }
    for (int i = 0; i < source.length(); i++) {
        loopPattern(source, index + 1, res + source.charAt(i));
    }
}

Upvotes: 3

SeniorJD
SeniorJD

Reputation: 7202

In current implementation, you should use:

for (int i=0; i <= input.size(); i++) {
   for(int j=0; j < input.size(); j++) {
      for(int k=0; k < input.size(); k++) {
         System.out.print(input.get(i));
         System.out.print(input.get(j));
         System.out.print(input.get(k));
         System.out.println();
      }
   }
}

But IMHO it is better to use s.charAt(i) instead of input.get(i).

Upvotes: 1

Related Questions