Created
October 10, 2019 15:46
-
-
Save portnov/584fa2e74486af561f4c4b3f19bf2e17 to your computer and use it in GitHub Desktop.
Merge arrays
This file contains 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 Control.Monad | |
import Data.Array.IO | |
import Data.Array.Base | |
import Data.Char (ord) | |
import qualified Data.ByteString as B | |
import qualified Data.ByteString.Char8 as C8 | |
addToIOArray :: IOUArray Int Int -> Int -> IO () | |
addToIOArray arr idx = do | |
val <- unsafeRead arr idx | |
unsafeWrite arr idx $ val + 1 | |
fillIOArray :: IOUArray Int Int -> IO () | |
fillIOArray arr = readLine >>= addList | |
where | |
readLine = parseLine <$> B.getLine | |
parseLine = tail . map parseInt . B.split (fromIntegral $ ord ' ') | |
parseInt str = case C8.readInt str of | |
Nothing -> error $ "not an integer: " ++ show str | |
Just (int, _) -> int | |
addList = mapM_ (addToIOArray arr) | |
printPair :: Show a => (a, Int) -> IO () | |
printPair (a, b) = replicateM_ b $ print a | |
main :: IO () | |
main = do | |
k <- read <$> getLine | |
arr <- newArray (0,100) 0 :: IO (IOUArray Int Int) | |
replicateM k $ fillIOArray arr | |
getAssocs arr >>= mapM_ printPair |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment