Can anybody see what i'm doing wrong here? I have an algorithm that encrypts a string by moving it 14 spaces along an array but when i try and decrypt it some of the letters are repeated for example
when encrypted: abcdefghijklmnopqrstuvwxyz == opqrstuvwxyzabcdefghijklmn
when decrypted: opqrstuvwxyzabcdefghijklmn == abcdefghijklklabcdefghijkl
char[] plaintext = input.toCharArray();
for(int i = 0; i<plaintext.length; i++) {
for(int j = 0 ; j<26; j++) {
if(j>=14 && plaintext[i]==alphabet[j]) {
plaintext[i] = alphabet[j-14];
break;
}
else if(plaintext[i] == alphabet[j] && j<14 ) {
plaintext[i] = alphabet [j+14] ;
}
}
}
The problem resides in the fact that the operation you apply is not the same when the character is >= 14
or < 14
, and it is also wrong since it may go over bounds.
What you do is:
18 (>= 14) -> 18 - 14 = 4
but 18 + 14 = 32 = 26+6
and 6 != 4
13 (<14) -> 13 + 14 = 27
which is out of bounds.The approach is not correct, you should make the value wrap over the alphabet array and this can be done easily with the mod %
operator:
newIndex = (oldIndex+shift) % alphabetLength
Without using the proper tools every a simple task becomes error prone and difficult to maintain. You could also do it without modulo but calculations should be correct, adding and subtracting 14
to the alphabet index surely doesn't create a valid mapping.