Created
April 29, 2014 08:03
-
-
Save ifukazoo/11393556 to your computer and use it in GitHub Desktop.
spacetalky問題回答
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import System.Environment | |
import System.Exit | |
import Control.Monad | |
import Data.Char | |
import qualified Data.List as List | |
main = do | |
argv <- getArgs | |
when (length argv /= 1) $ do | |
putStrLn "usage:command filename" | |
exitFailure | |
contents <- readFile(argv !! 0) | |
mapM_ putStrLn . map (anserString .List.dropWhileEnd isSpace) . lines $ contents | |
anserString :: String -> String | |
anserString line = | |
if canEncode line | |
then stretchString line ++ ":" ++ line | |
else "X:" ++ line; | |
canEncode :: String -> Bool | |
canEncode xs = let len = length xs | |
in | |
if len <= 2 | |
then True | |
else | |
if (len `mod` 2) == 1 | |
then False | |
else | |
let (x:(y:(z:zs))) = xs | |
in | |
if x == z && y /= 'z' | |
then False | |
else canEncode (z:zs) | |
stretchTwoChar :: String -> String | |
stretchTwoChar [] = [] | |
stretchTwoChar (x:[]) = [x] | |
stretchTwoChar (x:xs) = let num = toDecimal.head $ xs | |
in take num $ repeat x | |
stretchString :: String -> String | |
stretchString = concat . map stretchTwoChar . splitN 2 | |
splitN :: Int -> [a] -> [[a]] | |
splitN n array = let (before, remain) = splitAt n array | |
in case remain of | |
[] -> [before] | |
_ -> before : splitN n remain | |
toDecimal :: Char -> Int | |
toDecimal c = let a = "abcdefghijklmnopqrstuvwxyz" | |
in case (c `List.elemIndex` a) of | |
Nothing -> 0 | |
Just n -> n + 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment