Simple Encryption #1 - Alternating Split

题目

For building the encrypted string:
Take every 2nd char from the string, then the other chars, that are not every 2nd char, and concat them as new String.
Do this n times!

Examples:

1
2
"This is a test!", 1 -> "hsi  etTi sats!"
"This is a test!", 2 -> "hsi etTi sats!" -> "s eT ashi tist!"

Write two methods:

1
2
function encrypt(text, n)
function decrypt(encryptedText, n)

For both methods:
If the input-string is null or empty return exactly this value!
If n is <= 0 then return the input text.

思路

正则大佬牛逼!
加密方案很简单,就是把字符串奇偶位抽出来再合并成一个新字符串。因为位置从0开始算,所以奇偶位是相反的。
解密方案:把加密后的字符串切成奇数串和偶数串,然后根据输入位的奇偶性分别从奇偶串把字符取出来,取完之后直接slice掉取完的字符。

答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
function encrypt(text, n) {
if (n < 1 || !text) {
return text;
} else {
for (let i = 0; i < n; i++) {
let str_even = "";
let str_odd = "";
for (let j = 0; j < text.length; j++) {
(j % 2 === 0) ? (str_odd += text[j]) : (str_even += text[j]);
}
text = str_even + str_odd;
}
return text;
}

}

function decrypt(encryptedText, n) {
if (n < 1 || !encryptedText) {
return encryptedText;
} else {
//构建单次解密函数
function dec(enc_T) {
let decryptText = "";
//分割字符串
let str_odd = enc_T.slice(enc_T.length / 2);
let str_even = enc_T.slice(0, enc_T.length / 2);
for (let i = 0; i < enc_T.length; i++) {
if (i % 2 === 0) {
decryptText += str_odd[0];
str_odd = str_odd.slice(1);
} else {
decryptText += str_even[0];
str_even = str_even.slice(1);
}
}
return decryptText;
};
//判断解密次数
for (let i = 0; i < n; i++) {
encryptedText = dec(encryptedText);
}
return encryptedText;
}
}