js练习 Digital cypher

2018-11-22 08:43:12来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

Introduction
Digital Cypher assigns to each letter of the alphabet unique number. For example:

 a  b  c  d  e  f  g  h  i  j  k  l  m
 1  2  3  4  5  6  7  8  9 10 11 12 13
 n  o  p  q  r  s  t  u  v  w  x  y  z
14 15 16 17 18 19 20 21 22 23 24 25 26
Instead of letters in encrypted word we write the corresponding number, eg. The word scout:

 s  c  o  u  t
19  3 15 21 20
Then we add to each obtained digit consecutive digits from the key. For example. In case of key equal to 1939 :

   s  c  o  u  t
  19  3 15 21 20
 + 1  9  3  9  1
 ---------------
  20 12 18 30 21

   m  a  s  t  e  r  p  i  e  c  e
  13  1 19 20  5 18 16  9  5  3  5
+  1  9  3  9  1  9  3  9  1  9  3
  --------------------------------
  14 10 22 29  6 27 19 18  6  12 8
Task
Write a function that accepts str string and key number and returns an array of integers representing encoded str.

Input / Output
The str input string consists of lowercase characters only.
The key input number is a positive integer.

Example
Encode("scout",1939);  ==>  [ 20, 12, 18, 30, 21]
Encode("masterpiece",1939);  ==>  [ 14, 10, 22, 29, 6, 27, 19, 18, 6, 12, 8]

 

最多赞

1 function encode(str, n) {
2   const key = String(n)
3   return Array.from(str, (c, i) => c.charCodeAt(0) - 96 + Number(key[i % key.length]))
4 }

 

比较好

1 function encode(str, num) {
2   var key = num.toString();
3   return str.split('').map(function(char, i) {
4     return char.charCodeAt(0) - 96 + +key[i % key.length];
5   });
6 }

我的方法:

 1 function encode(str,  n)
 2 {
 3   var result=[];
 4   var num=n+"";
 5   for(var i=0;i<str.length;i++)
 6   {
 7     if((i+1)%num.length==0)
 8     {
 9        result[result.length]=str.charCodeAt(i)-96+Number(num[num.length-1]);
10     }
11     else
12     {
13        result[result.length]=str.charCodeAt(i)-96+Number(num[(i+1)%num.length-1]);
14     }
15    
16     if(i<str.length-1)
17     {
18     str[i]+=",";
19     }
20   }
21   return result;
22 }

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:【css】 如何修改select的样式

下一篇:开发中常用的JS知识点集锦