Avatar of atmantree

atmantree's solution

to Rail Fence Cipher in the Haskell Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

Implement encoding and decoding for the rail fence cipher.

The Rail Fence cipher is a form of transposition cipher that gets its name from the way in which it's encoded. It was already used by the ancient Greeks.

In the Rail Fence cipher, the message is written downwards on successive "rails" of an imaginary fence, then moving up when we get to the bottom (like a zig-zag). Finally the message is then read off in rows.

For example, using three "rails" and the message "WE ARE DISCOVERED FLEE AT ONCE", the cipherer writes out:

W . . . E . . . C . . . R . . . L . . . T . . . E
. E . R . D . S . O . E . E . F . E . A . O . C .
. . A . . . I . . . V . . . D . . . E . . . N . .

Then reads off:

WECRLTEERDSOEEFEAOCAIVDEN

To decrypt a message you take the zig-zag shape and fill the ciphertext along the rows.

? . . . ? . . . ? . . . ? . . . ? . . . ? . . . ?
. ? . ? . ? . ? . ? . ? . ? . ? . ? . ? . ? . ? .
. . ? . . . ? . . . ? . . . ? . . . ? . . . ? . .

The first row has seven spots that can be filled with "WECRLTE".

W . . . E . . . C . . . R . . . L . . . T . . . E
. ? . ? . ? . ? . ? . ? . ? . ? . ? . ? . ? . ? .
. . ? . . . ? . . . ? . . . ? . . . ? . . . ? . .

Now the 2nd row takes "ERDSOEEFEAOC".

W . . . E . . . C . . . R . . . L . . . T . . . E
. E . R . D . S . O . E . E . F . E . A . O . C .
. . ? . . . ? . . . ? . . . ? . . . ? . . . ? . .

Leaving "AIVDEN" for the last row.

W . . . E . . . C . . . R . . . L . . . T . . . E
. E . R . D . S . O . E . E . F . E . A . O . C .
. . A . . . I . . . V . . . D . . . E . . . N . .

If you now read along the zig-zag shape you can read the original message.

Getting Started

For installation and learning resources, refer to the exercism help page.

Running the tests

To run the test suite, execute the following command:

stack test

If you get an error message like this...

No .cabal file found in directory

You are probably running an old stack version and need to upgrade it.

Otherwise, if you get an error message like this...

No compiler found, expected minor version match with...
Try running "stack setup" to install the correct GHC...

Just do as it says and it will download and install the correct compiler version:

stack setup

Running GHCi

If you want to play with your solution in GHCi, just run the command:

stack ghci

Feedback, Issues, Pull Requests

The exercism/haskell repository on GitHub is the home for all of the Haskell exercises.

If you have feedback about an exercise, or want to help implementing a new one, head over there and create an issue. We'll do our best to help you!

Source

Wikipedia https://en.wikipedia.org/wiki/Transposition_cipher#Rail_Fence_cipher

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

Tests.hs

{-# LANGUAGE RecordWildCards #-}

import Data.Foldable     (for_)
import Test.Hspec        (Spec, describe, it, shouldBe)
import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith)

import RailFenceCipher (encode, decode)

main :: IO ()
main = hspecWith defaultConfig {configFastFail = True} specs

specs :: Spec
specs = do
          describe "encode" $ for_ encodeCases testE
          describe "decode" $ for_ decodeCases testD
  where
    testE Case{..} = it description $ encode key text `shouldBe` expected
    testD Case{..} = it description $ decode key text `shouldBe` expected

data Case = Case { description :: String
                 , key         :: Int
                 , text        :: String
                 , expected    :: String
                 }

encodeCases :: [Case]
encodeCases = [ Case { description = "encode with two rails"
                     , key         = 2
                     , text        = "XOXOXOXOXOXOXOXOXO"
                     , expected    = "XXXXXXXXXOOOOOOOOO"
                     }
              , Case { description = "encode with three rails"
                     , key         = 3
                     , text        = "WEAREDISCOVEREDFLEEATONCE"
                     , expected    = "WECRLTEERDSOEEFEAOCAIVDEN"
                     }
              , Case { description = "encode with ending in the middle"
                     , key         = 4
                     , text        = "EXERCISES"
                     , expected    = "ESXIEECSR"
                     }
              ]

decodeCases :: [Case]
decodeCases = [ Case { description = "decode with three rails"
                     , key         = 3
                     , text        = "TEITELHDVLSNHDTISEIIEA"
                     , expected    = "THEDEVILISINTHEDETAILS"
                     }
              , Case { description = "decode with five rails"
                     , key         = 5
                     , text        = "EIEXMSMESAORIWSCE"
                     , expected    = "EXERCISMISAWESOME"
                     }
              , Case { description = "decode with six rails"
                     , key         = 6
                     , text        = "133714114238148966225439541018335470986172518171757571896261"
                     , expected    = "112358132134558914423337761098715972584418167651094617711286"
                     }
              ]
module RailFenceCipher (encode, decode) where

import Data.List

generateFencePortion :: Int -> Int -> [Int]
generateFencePortion n msgLength = take msgLength (cycle $ [1.. n-1] ++ [n, n-1 ..2])

generateEncoding :: Int -> [Char] -> [(Char, Int)]
generateEncoding n str = zip str (generateFencePortion n $ length str)

generateDecodeSequence :: Int -> [Char] -> [(Char, Int)]
generateDecodeSequence n str = zip str (sort (generateFencePortion n $ length str))

takeChar :: [Int] -> [(Char, Int)] -> [Char]
takeChar seq decoSeq = [ fst . head . snd $ break (\x -> snd x == (head seq)) decoSeq ]

newList :: [Int] -> [(Char, Int)] -> [(Char, Int)]
newList seq decoSeq = (fst $ break (\x -> snd x == (head seq)) decoSeq) ++
                      (tail . snd $ break (\x -> snd x == (head seq)) decoSeq)

decodeProto :: [Int] -> [Char] -> [(Char, Int)] -> [Char]
decodeProto seq accum decoSeq
  | seq == []  = accum
  | otherwise  = decodeProto (tail seq)
                             (accum ++ (takeChar seq decoSeq))
                             (newList seq decoSeq)

encode :: Int -> String -> String
encode n str = concat [map (\y -> fst y) 
                            (filter (\x -> snd x == m) 
                            (generateEncoding n str))
                            | m <- [1..n]]

decode :: Int -> String -> String
decode n str = decodeProto (generateFencePortion n (length str))
                           ""
                           (generateDecodeSequence n str)

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?