DEV Community

Discussion on: Daily Challenge #72 - Matrix Shift

Collapse
 
avalander profile image
Avalander • Edited

Haskell

shift :: Int -> [String] -> [String]
shift n m =
  foldr unflatten [""] shifted
  where
    columns  = length $ head m
    flat_m   = concat m
    split_at = (length flat_m) - n
    shifted  = (drop split_at flat_m) ++ (take split_at flat_m)
    unflatten :: Char -> [String] -> [String]
    unflatten y (x:xs)
      | length x == columns = [y] : x : xs
      | otherwise           = ([y] ++ x) : xs

Basically the algorithm is as follows:

  1. Flatten the matrix.
  2. Take the n last elements and prepend them to the beginning of the list.
  3. Unflatten the matrix.
-- In haskell strings are lists of chars, so "abcd" is the same as ['a','b','c','d'] but shorter to type.
shift 1 [ "abcd", "1234", "code", "blah" ]
-- [ "habc", "d123", "4cod", "ebla" ]
Collapse
 
not_jffrydsr profile image
@nobody

simple. 👍🏿
i still feel like Haskell has too many non-alpha characters in the syntax set. 🙄

Collapse
 
avalander profile image
Avalander

Haha, yeah, it's marginally easier once you get used to them though.

Thread Thread
 
not_jffrydsr profile image
@nobody

i'll take your word for it and stay in my (((safe (space)))) for now . . .
🤗