Featured post
algorithm - Simple row transposition cipher -
for lisp class, given simple row transposition cipher homework, tried solve in haskell, too. basically, 1 splits string rows of length n, , transposes result. concatenation of resulting list of lists of chars encrypted string. decoding little harder, since there may missing elements in last row of input (incomplete columns in result), have taken care of.
this solution in haskell:
import data.list import data.ratio import data.list.split encode :: string -> int -> string encode s n = concat . transpose $ chunk n s decode :: string -> int -> string decode s n = take len $ encode s' rows s' = foldr (insertat " ") s idxs rows = ceiling (len % n) idxs = take (n-filled) [n*rows-1,(n-1)*rows-1..] filled = len - n * (rows - 1) len = length s insertat :: [a] -> int -> [a] -> [a] insertat xs ys = pre ++ xs ++ post (pre,post) = splitat ys it job, not sure, whether considered idiomatic haskell, since fiddling indices not feel declarative. improved, , if yes, how?
by way: there akin insertat in haskell 98? i.e. function inserting element or list @ given index list.
note: not part of homework, due today anyway.
i looking @ encode , decode problems differently. encode breaks data n-column matrix, transposes (into n-row matrix) , concatenates rows. decode breaks data n row matrix, transposes (into n columm matrix) , concatenates rows.
so i'd start defining 2 functions - 1 make array n column matrix:
chunk:: int -> [a] -> [[a]] chunk n = chunk' n (length as) chunk' n l | l <= n = [as] | otherwise = : chunk' n (l-n) rest (some, rest) = splitat n and slice array n row matrix:
slice :: int -> [a] -> [[a]] slice n = chunk (q+1) front ++ chunk q (q,r) = length `divmod` n (front, back) = splitat (r*(q+1)) now, encoding , decoding easy:
encode :: int -> [a] -> [a] encode = ((concat . transpose) .). chunk decode :: int -> [a] -> [a] decode = ((concat . transpose) .). slice - Get link
- X
- Other Apps
Comments
Post a Comment