Skip to content

Instantly share code, notes, and snippets.

@willnet
Created September 4, 2012 07:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willnet/3618060 to your computer and use it in GitHub Desktop.
Save willnet/3618060 to your computer and use it in GitHub Desktop.
http://qiita.com/items/9d80de41903775296ca6 の問題を haskell で解いてみた
import Data.Char
import Test.HUnit
import System.Environment
data Image = Image Int String
instance Show Image where
show (Image l d) = "Image " ++ [(intToDigit l)] ++ ":" ++ (apply $ appendZero d)
appendZero :: String -> String
appendZero d = if m == 0
then d
else d ++ (take (4 - m) $ repeat '0')
where
m = (length d) `mod` 4
apply :: String -> String
apply [] = []
apply (a:b:c:d:xs) = bin2hex [a,b,c,d] : apply xs
initializeImage :: String -> Image
initializeImage string = Image l dt
where
[(l,':':d)] = reads string :: [(Int, String)]
dt = take (l * l) $ foldr (\x acc -> (hex2bin x) ++ acc) "" d
bin2hex :: String -> Char
bin2hex = intToDigit . foldl (\acc x -> (digitToInt x) + acc * 2) 0
hex2bin :: Char -> String
hex2bin x = if (length bin) == 4
then bin
else (take (4 - length bin) (repeat '0')) ++ bin
where
bin = cal $ digitToInt x
cal :: Int -> String
cal 0 = []
cal x = cal d ++ [intToDigit m]
where (d, m) = x `divMod` 2
turnImage :: Image -> Image
turnImage (Image l d) = Image l newData
where
indexes = turnIndexes l
newData = foldr (\x acc -> (d !! x) : acc) [] indexes
turnIndexes :: Int -> [Int]
turnIndexes x = gv x (x * x - x)
gv x t
| t < x * x = calTurnIndexes x t ++ gv x (t + 1)
| otherwise = []
calTurnIndexes :: Int -> Int -> [Int]
calTurnIndexes x t
| t < 0 = []
| otherwise = t : calTurnIndexes x (t - x)
tests = test [[6,3,0,7,4,1,8,5,2] ~=? turnIndexes 3]
main = do
args <- getArgs
let im = initializeImage . head $ args
tim = turnImage im
print tim
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment