Created
November 20, 2023 11:21
-
-
Save Git-I985/7f18c3e537031575d6bef8bd3a8030cd to your computer and use it in GitHub Desktop.
Rail fence cipher
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 getSteps(currentRail, numberRails) { | |
let step1 = (currentRail === numberRails) || (currentRail === 1) ? ((numberRails - 1) * 2) : ((numberRails - currentRail) * 2); | |
let step2 = (currentRail === numberRails) || (currentRail === 1) ? (step1) : ((currentRail - 1) * 2); | |
return [step1, step2] | |
} | |
function encodeRailFenceCipher(string, numberRails) { | |
let res = '' | |
for (let currentRail = 1; currentRail <= numberRails; currentRail++) { | |
const [step1, step2] = getSteps(currentRail, numberRails) | |
let step; | |
for (let letter = currentRail - 1; letter < string.length; letter += step) { | |
res += string[letter] | |
step = step === step1 ? step2 : step1 | |
} | |
} | |
return res | |
} | |
function decodeRailFenceCipher(string, numberRails) { | |
let res = [] | |
const iterator = string[Symbol.iterator]() | |
for (let currentRail = 1; currentRail <= numberRails; currentRail++) { | |
const [step1, step2] = getSteps(currentRail, numberRails) | |
let step; | |
for (let letterIndex = currentRail - 1; letterIndex < string.length; letterIndex += step) { | |
res[letterIndex] = iterator.next().value | |
step = step === step1 ? step2 : step1 | |
} | |
} | |
return res.join('') | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment