5
\$\begingroup\$

I am making a simple transposition cipher. I am testing the program with the word "computer" with the secret key "5,2,8,3,7,1,4,6", where the encrypt method will put the 5th letter 'u' in the first position, 2nd letter 'o' in 2nd position, 8th letter 'r' in 3rd position...

So the output would be:
original: computer
encrypted:uormecpt
decrypted:computer

Right now my decrypt method is of O(n^2). How can I make this faster?

Where char[] y would be uormecpt. The z[j] - 1 is the offset as my iterator starts from 0, but my key starts at 1.

public static char[] decrypt(char[] y, int[] z)
{
 char[] decrypted = new char[y.length];
 for (int i = 0; i < y.length; i++)
 {
 for (int j = 0; j < y.length; j++)
 {
 if (i == z[j]-1)
 decrypted[i] = y[j];
 }
 }
 return decrypted;
}
David Harkness
8,8931 gold badge27 silver badges44 bronze badges
asked Apr 16, 2011 at 18:16
\$\endgroup\$

1 Answer 1

7
\$\begingroup\$

If you can assume that every index in the encrypted message is included in the key, You can loop over the key and encrypted message together, placing each letter into the correct decrypted message slot directly:

public static char[] decrypt(char[] encrypted, int[] key)
{
 char[] decrypted = new char[encrypted.length];
 for (int i = 0; i < encrypted.length; i++)
 {
 decrypted[key[i]] = encrypted[i];
 }
 return decrypted;
}
answered Apr 16, 2011 at 18:57
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.