0

I have seen a lot of solutions to this but still didn't found the efficient solution for wrapping around for the non-alphabet character in the text to be encrypted.

What I did was jth position (position of key) = ith position % length_vigenere_key_word; This exactly wraps around for each of the key but when it comes to non-alphabet character it still wraps.

I tried to find optimal solution but is helpless with it. I have seen people using two for loop variable, some using variable to hold position of key.

2

I am among those people who suggest you to use 2 loop variables, actually its 1. Use a variable (say i) to iterate over each element of the input string and maintain another variable (say j) to hover over the key in the same loop. Consider the string to be array, then to eliminate wrapping over non-alphabetical characters, do the following in loop.

if ((array[i] >= 'a' && array[i] <= 'z') || (array[i] >= 'A' && array[i] <= 'Z'))
{
     // code for converting input text string
}
else
{
     --j;
}

You could also use the isalpha() function defined in ctype.h header. The code simply decrements j by 1 when it is the case of a non-alphabetical character. It should be noted that the above code is with respect to the nature of code which does not attempt to handle the non-alphabetical character. If you have already written a code that fails on this, and now are writing it again from scratch to make your code handle this situation, then its better to do something like below:

j = 0 
for i in range 0 to len(array): do
    while array[i] is not an alphabet and i < len(array): then
        ++i
    //do conversions
    j = (j+1) % len(key)

Both of the above suggestions are under the assumption that there is no non-alphabetical character in key, if you consider one, then add this in the for loop in pseudocode

while key[j] is not an alphabet and j < len(key): then
    ++j

Hope that helps. Good Luck.

2
  • If you are having a separate loop for j then why do j = j+1%len(key); that seems redundant. Ain't it. You can just check over the if j > len(key) and reset it to 0, while string is alphabet. – Birat Jan 29 '15 at 16:31
  • Talking about the last code snippet? Its to check for non-alphabetical character in key, not in array, and I suppose that's not in the pset spec, I just mentioned it as a separate problem. So there is no redudancy imo – sinister Jan 29 '15 at 16:48
1

another way to do it

j++;
j = j % v;

where j is the jth char of key and v is strlen of key. when placed at the end of your shift functions within your if statement, j will increment only when you've executed your shift functions. so if plaintext[i] is not alpha it doesn't increment.

as opposed to

j = i % v;

while it will wrap, it increments j regardless of isalpha

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .