Editor

Rail Fence Cipher

#94 · Strings · Intermediate · 75 XP · about 14 min

The rail fence cipher writes a message in a zigzag across a number of rows called rails: the first character goes on the top rail, the next ones step down one rail at a time to the bottom rail, then climb back up to the top, and so on. Reading each rail from left to right, top rail first, gives the encrypted text.

Write rail_fence(text, rails) that returns the encrypted text. Every character, spaces included, is placed on a rail. With one rail, or with at least as many rails as characters, the text does not change.

Examples

rail_fence("WEAREDISCOVERED", 3)  # returns 'WECRERDSOEEAIVD'
rail_fence("HELLO", 2)            # returns 'HLOEL'
rail_fence("HELLO", 1)            # returns 'HELLO'

With 3 rails, "WEAREDISCOVERED" is laid out like this, and reading the rows gives "WECR" + "ERDSOEE" + "AIVD":

W . . . E . . . C . . . R . .
. E . R . D . S . O . E . E .
. . A . . . I . . . V . . . D

Constraints

  • text has 0 to 10,000 characters.
  • 1 <= rails <= 1000

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.