Untitled
unknown
javascript
a year ago
847 B
5
Indexable
Never
function decodeRailFenceCipher(ciphertext, rails) { const zigzag = []; for (let i = 0; i < rails; i++) { zigzag.push([]); } let rail = 0; let direction = 1; for (let i = 0; i < ciphertext.length; i++) { zigzag[rail].push(null); rail += direction; if (rail === rails - 1 || rail === 0) { direction = -direction; } } let index = 0; for (let i = 0; i < rails; i++) { for (let j = 0; j < zigzag[i].length; j++) { if (zigzag[i][j] === null) { zigzag[i][j] = ciphertext[index++]; } } } rail = 0; direction = 1; let plaintext = ''; for (let i = 0; i < ciphertext.length; i++) { plaintext += zigzag[rail][0]; zigzag[rail].splice(0, 1); rail += direction; if (rail === rails - 1 || rail === 0) { direction = -direction; } } return plaintext; }