Thursday, July 18, 2013

String Permutation in java

package com.swain;

public class Permutation {

    public static void main(String args[]) throws Exception {
        String str = "abc";
        System.out.println("String is " + str);
        System.out.println("*********************");
        System.out.println("After Permutation ");
        showString("", str);
    }

    public static void showString(String st, String str) {
        if (str.length() <= 1)
            System.out.println(st + str);
        else
            for (int i = 0; i < str.length(); i++) {
                String newValue = str.substring(0, i) + str.substring(i + 1);
                showString(st + str.charAt(i), newValue);
            }
    }

}
************************************
or
 ************************************
package com.swain;

public class Permutation {
    static String permutationStr[];
    static int indexStr = 0;

    static int factorial(int i) {
        if (i == 1)
            return 1;
        else
            return i * factorial(i - 1);
    }

    public static void permutation(String str) {
        char strArr[] = str.toLowerCase().toCharArray();
        java.util.Arrays.sort(strArr);

        int count = 1, dr = 1;
        for (int i = 0; i < strArr.length - 1; i++) {
            if (strArr[i] == strArr[i + 1]) {
                count++;
            } else {
                dr *= factorial(count);
                count = 1;
            }
        }
        dr *= factorial(count);

        count = factorial(strArr.length) / dr;

        permutationStr = new String[count];

        permutation("", str);

        for (String oneStr : permutationStr) {
            System.out.println(oneStr);
        }
    }

    private static void permutation(String prefix, String str) {
        int n = str.length();
        if (n == 0) {
            for (int i = 0; i < indexStr; i++) {
                if (permutationStr[i].equals(prefix))
                    return;
            }
            permutationStr[indexStr++] = prefix;
        } else {
            for (int i = 0; i < n; i++) {
                permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
            }
        }
    }

    public static void main(String arg[]) {
        Permutation p = new Permutation();
        p.permutation("aaa");
    }
}

output :


No comments:

Post a Comment

How ChatGPT can Benefit Coding: Your Guide to Leveraging an AI Language Model

 Introduction: Hello, coders! Welcome to this blog post on how ChatGPT, an AI language model, can benefit your coding skills and projects. A...