Created
May 17, 2019 00:30
-
-
Save backslash112/113665b5c206bb3bee64c48e2b988e4e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function decrypt(word) { | |
// string to char array | |
let chars = []; | |
for (let c of word) { | |
chars.push(c); | |
} | |
// step 3 | |
let asciiValues = chars.map(c => c.charCodeAt(0)); | |
console.log(asciiValues); | |
// step 2 | |
let nums = []; | |
for (let i = 0; i < asciiValues.length; i++) { | |
let num = asciiValues[i]; | |
let pre = 0; | |
if (i === 0) { | |
pre = 1; | |
} else { | |
pre = nums[i-1]; | |
} | |
while (!inRange(num - pre)) { | |
num += 26; | |
} | |
nums.push(num); | |
} | |
// step 1 | |
let originAsciiValues = new Array(nums.length); | |
let i = nums.length-1; | |
while (i > 0) { | |
originAsciiValues[i] = nums[i] - nums[i-1]; | |
i--; | |
} | |
if (nums[0]) { | |
originAsciiValues[0] = nums[0]-1; | |
} | |
console.log(originAsciiValues); | |
// convert | |
let res = originAsciiValues.map(num => String.fromCharCode(num)); | |
return res.join(''); | |
} | |
function inRange(num) { | |
return num >= 97 && num <= 122; | |
} | |
const res = decrypt('dnotq'); | |
console.log(res); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment