Wednesday, March 9, 2016

CAESARS CIPHER

In this challenge we have to decode a cipher message. More about cipher can be found out here.

So we have a simplest and most widely known ciphers called Caesar cipher, also called shift cipher. Basically in a shift cipher the meanings of the letters are shifted by some set value.

An example of this type of modern cipher is the ROT13 cipher, where the values of the letters are shifted by 13 places. Thus 'A' ↔ 'N', 'B' ↔ 'O' and so on.

So we have to write a function which takes a ROT13 encoded string as input and returns a decoded string.

Other conditions are:-

1.  All letters should be uppercase.

2.  Non-alphabetic character i.e. spaces and punctuation's are not to be transformed, but have to be passed on.

At last the list of clues in the form of helpful links are as follows:
It took me very less time to implement the algorithm. In this algorithm I loop thorough all the string elements converting each of them to equivalent uni-code values and then pushing them to the array. Finally I joined all the elements using the join() method of arrays.

                 function rot13(str) { // LBH QVQ VG!
                 arr = [];
                 for (var i = 0; i < str.length; i++){
                     var a = str.charCodeAt(i);
                     if(a >= 65 && a <= 77){
                         a += 13;
                     } else if(a >= 78 && a <= 90){
                         a -= 13;
                     } else {
                       a = a;
                     }
                     var c = String.fromCharCode(a);
                     arr.push(c);
                }
            }

No comments:

Post a Comment