How to retrieve the original string from the shuffled string of a Java algorithm

M.zK :

I have an algorithm for Java that shuffles a string. I already have the output of the shuffled string and the algorithm that shuffled it...

static String Validate(String f) {
    StringBuilder str = new StringBuilder(f);

    for (int i = 0; i < str.length(); i++) {
        for (int j = i; j < str.length()-1; j++) {
            char t = str.charAt(j);
            str.setCharAt(j, str.charAt(j+1));
            str.setCharAt(j + 1, t);
        }
    }

    System.out.print(str);

    return "" + str.toString();
}

and the output string is...

lgcnyurVr34d0Df{__3_R}43na501

My question is: how to retrieve the original string?

xenteros :

Yes, it is possible to revert the process. The original String was flag{c4n_y0u_r3V3r53_4ndR01D}

The original algorithms makes the following steps:

0 0 ABCDEF
0 1 BACDEF
0 2 BCADEF
0 3 BCDAEF
0 4 BCDEAF
1 1 BCDEFA  //A is at the end now
1 2 BDCEFA
1 3 BDECFA
1 4 BDEFCA
2 2 BDEFAC  //C was at index 2 at the beginning of this outer loop iteration
2 3 BDFEAC
2 4 BDFAEC
3 3 BDFACE  //now E went to the end of the String
3 4 BDFCAE
4 4 BDFCEA

To revert it, one needs to reverse the direction of the loops and the direction the letters are swapped.

static String reverseValidate(String reversed) {
    StringBuilder str = new StringBuilder(reversed);

    for (int i = str.length() - 1; i >= 1; i--) {
        for (int j = str.length() - 1; j >= i; j--) {
            char t = str.charAt(j);
            str.setCharAt(j, str.charAt(j - 1));
            str.setCharAt(j - 1, t);
        }
    }

    return str.toString();
}

The algorith you have posted works it the following way: For each index in the string length, it starts from this index and moves that letter to the end.

To see it, try printing System.out.println(i + " " + j + " " + str); somewhere in the inner loop.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=81387&siteId=1