Skip to content

Commit 18e2e3f

Browse files
committed
Solve 'Circle cipher' kata
1 parent 9af6336 commit 18e2e3f

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/CircleCipher.hs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
module CircleCipher (encode, decode) where
2+
3+
-- https://www.codewars.com/kata/634d0723075de3f97a9eb604/train/haskell
4+
5+
import Data.List (sortOn)
6+
7+
encode :: [a] -> [a]
8+
encode xs = take size . concatMap (\(c1, c2) -> [c1, c2]) . zip xs . reverse $ xs
9+
where
10+
size = length xs
11+
12+
decode :: [a] -> [a]
13+
decode xs = map snd . sortOn fst . zip indices $ xs
14+
where
15+
size = length xs
16+
indices = encode [0 .. size - 1]

test/CircleCipherSpec.hs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
module CircleCipherSpec where
2+
3+
import CircleCipher (decode, encode)
4+
import Test.Hspec
5+
6+
spec :: Spec
7+
spec = do
8+
describe "Fixed Tests" $ do
9+
let tests =
10+
[ ("codewars", "csordaew"),
11+
("white", "wehti"),
12+
("Assert", "Atsrse"),
13+
("Hello world!", "H!edlllroo w"),
14+
("You have chosen to translate this kata.", "Y.oaut ahka vsei hcth oesteanl stnoa rt")
15+
]
16+
it "encodes properly" $ do
17+
mapM_ (\(s, s') -> encode s `shouldBe` s') tests
18+
it "decodes properly" $ do
19+
mapM_ (\(s, s') -> decode s' `shouldBe` s) tests
20+
21+
describe "Additional Tests" $ do
22+
it "encodes ints" $ do
23+
encode [0, 1, 2, 3, 4, 5, 6, 7] `shouldBe` [0, 7, 1, 6, 2, 5, 3, 4]
24+
it "decodes ints" $ do
25+
decode [0, 7, 1, 6, 2, 5, 3, 4] `shouldBe` [0, 1, 2, 3, 4, 5, 6, 7]

0 commit comments

Comments
 (0)