# rail fence cipher
def encrypt(text, rails):
    fence = [""] * rails
    row = 0
    step = 1
    for ch in text:
        fence[row] += ch
        if row == 0:
            step = 1
        elif row == rails - 1:
            step = -1
        row += step
    return "".join(fence)

def decrypt(cipher, rails):
    # find the zig zag pattern first
    pattern = []
    row = 0
    step = 1
    for i in range(len(cipher)):
        pattern.append(row)
        if row == 0: step = 1
        elif row == rails-1: step = -1
        row += step

    result = [""] * len(cipher)
    k = 0
    for r in range(rails):
        for i in range(len(cipher)):
            if pattern[i] == r:
                result[i] = cipher[k]
                k += 1
    return "".join(result)


msg = "HELLOWORLD"
c = encrypt(msg, 3)
print("message  :", msg)
print("encrypted:", c)
print("decrypted:", decrypt(c, 3))
