Advertisement
dimipan80

Exams - Moving Letters

Nov 13th, 2014
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* The input message is given as a sequence of words separated by a space. The words are converted into
  2.  a sequence of letters the following way: until all words disappear, the last letter of each word (if exists)
  3.  is removed from the word and is appended to the output sequence of letters.
  4.  The next step in the encryption algorithm is to move each letter (from positions 0, 1, …, n-1) on the right k times. The number k is taken from the number of the letter in the Latin alphabet regardless of its casing ('a'  1, 'b'  2, …, 'z'  26). When a letter is moved to the right, if it is the last letter of the sequence, its next position is the first position in the sequence, just before all the letters. */
  5.  
  6. function solve(args) {
  7.     args = args[0].split(/[^a-z]+/i).filter(Boolean);
  8.     var maxWordLength = 1;
  9.     args.forEach(function(word) {
  10.         maxWordLength = (word.length > maxWordLength) ? word.length : maxWordLength;
  11.         return maxWordLength;
  12.     });
  13.  
  14.     var lettersSeqArr = [];
  15.     for (var i = 0; i < maxWordLength; i += 1) {
  16.         for (var word in args) {
  17.             if (args.hasOwnProperty(word)) {
  18.                 var wordArr = (args[word]).split('').filter(Boolean);
  19.                 wordArr.reverse();
  20.                 if (wordArr[i]) {
  21.                     lettersSeqArr.push(wordArr[i]);
  22.                 }
  23.             }
  24.         }
  25.     }
  26.  
  27.     Array.prototype.insertAt = function(index, element1) {
  28.         if (index >= 0) {
  29.             this.splice(index, 0, element1);
  30.         }
  31.     };
  32.  
  33.     Array.prototype.removeFrom = function(index, countElemToRemove) {
  34.         if (index >= 0 && index < this.length) {
  35.             this.splice(index, countElemToRemove);
  36.         }
  37.     };
  38.  
  39.     for (i = 0; i < lettersSeqArr.length; i += 1) {
  40.         var currentLetter = lettersSeqArr[i];
  41.         var movingPositionsLetter = currentLetter.toLowerCase().charCodeAt(0) - 96;
  42.         movingPositionsLetter = (movingPositionsLetter + i) % lettersSeqArr.length;
  43.         lettersSeqArr.removeFrom(i, 1);
  44.         lettersSeqArr.insertAt(movingPositionsLetter, currentLetter);
  45.     }
  46.  
  47.     console.log(lettersSeqArr.join(''));
  48. }
  49.  
  50. solve(['Fun exam right']);
  51. solve(['Hi exam']);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement