fork(3) download
  1. import Data.Function
  2. import qualified Data.List as L
  3. import qualified Data.Map as M
  4.  
  5. sp :: Char
  6. sp = '_'
  7.  
  8. alignColumn :: [String] -> [String]
  9. alignColumn = L.transpose . f . L.transpose . addsp
  10. where
  11. addsp xss = map add xss
  12. where maxlen = foldr (\x a -> if length x > a then length x else a) 0 xss
  13. add xs = xs ++ replicate (maxlen - length xs) sp
  14. f [] = []
  15. f xss = g $ do
  16. is <- groupOfIndex $ head xss
  17. let (ys:yss) = insertSP xss is
  18. return $ ys : f yss
  19. g [] = []
  20. g xs = L.minimumBy (compare `on` length) xs
  21.  
  22. insertSP :: [String] -> [Int] -> [String]
  23. insertSP xss1 is = f xss1 pre
  24. where
  25. pre = zipWith (\k _ -> if elem k is then Nothing else Just sp) [0..] (head xss1)
  26. f [] cs
  27. | all (== Nothing) cs = []
  28. | otherwise = foldr (\x acc -> maybe sp id x : acc) [] cs : []
  29. f (xs:xss) cs = (map fst ys) : f xss (map snd ys)
  30. where
  31. ys = zipWith g xs cs
  32. where
  33. g x Nothing = (x, Nothing)
  34. g x (Just c) = (c, Just x)
  35.  
  36. groupOfIndex :: String -> [[Int]]
  37. groupOfIndex xs = map (spi++) . M.elems . fst . foldl f (M.empty, 0) $ xs
  38. where
  39. spi = L.findIndices (==sp) xs
  40. f (acc,i) x
  41. | x == sp = (acc, i+1)
  42. | otherwise = (M.insertWith (++) x [i] acc, i+1)
  43.  
  44. main :: IO ()
  45. main = do
  46. run ["1","1"]
  47. run ["1","2"]
  48. run ["12", "21"]
  49. run ["11", "12"]
  50. run ["113", "114"]
  51. run ["123", "134"]
  52. run ["1212", "1322", "1122"]
  53. run ["123", "113", "1323"]
  54. run ["1234", "4321", "1122"]
  55. -- run ["12121313432121233", "21322312443213443"]
  56. where
  57. run xs = do
  58. putStrLn . unlines $ alignColumn xs
  59.  
Success #stdin #stdout 0s 6284KB
stdin
Standard input is empty
stdout
1
1
1
1

1
2
1_
_2

12
21
12_
_21

11
12
11_
1_2

113
114
113_
11_4

123
134
123_
1_34

1212
1322
1122
1__212
1_32_2
11_2_2

123
113
1323
1__23
113__
1_323

1234
4321
1122
1_234___
____4321
112___2_