1
\$\begingroup\$

I am doing a project and I have come up with some code to swap every letter with every other letter in a string, only the project was to be "efficient as possible".

Example:

"rya" = yra, ray, ayr.. etc

I understand exactly how the code works. I would just like to make it efficient as possible.

public String testSwap(String word) {

char[] charArr = word.toCharArray();
char[] charArr2 = new char[word.length()];
String newString = "";

for(int i = 0; i < word.length(); i++) {
    for(int j = 0; j < word.length(); j++) {
        int count = 0;

        for(char c: charArr) {
            charArr2[count] = c;
            count++;
        }

        if(charArr2[i] != charArr[j]) {
            charArr2[i] = charArr[j];
            charArr2[j] = charArr[i];

            newString = new String(charArr2);

            if(graph.keySet().contains(newString)) {
                return newString;
            } else {
                newString = "";
            }
        }
    }
}
return newString;
}

NOTE: The if statement inside is for the current project I am doing.

\$\endgroup\$
0
\$\begingroup\$

to swap every letter with every other letter in a string

In other words you need all permutations of a string. Ok not all: no need in null set.

I would just like to make it efficient as possible.

Just wanted to show you another solution. A crazy one with a recursion: https://stackoverflow.com/questions/4240080/generating-all-permutations-of-a-given-string

public static void permutation(String str) { 
    permutation("", str); 
}

private static void permutation(String prefix, String str) {
    int n = str.length();
    if (n == 0) System.out.println(prefix);
    else {
        for (int i = 0; i < n; i++)
            permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
    }
}

Quick solution to get it in one line with commas:

public static String permutation(String str) {
        String res = permutation("", str);
        return res.substring(0, res.length()-2);
    }

private static String permutation(String prefix, String str) {
    String res = "";
    int n = str.length();
    if (n == 0) res = res + prefix + ", ";
    else {
         for (int i = 0; i < n; i++)
             res = res + permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
    }
    return res;
 }

Output: rya, ray, yra, yar, ary, ayr

Less code, but definitely not the most efficient: calling charAt and substring a lot of time - not a good way.

In that link there are alot of other examples how to do it.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.