Created
October 10, 2019 16:19
-
-
Save portnov/0d76663e9b1759294d94147b9f48680a to your computer and use it in GitHub Desktop.
Merge arrays #2
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
{-# LANGUAGE OverloadedStrings #-} | |
import Control.Monad | |
import Data.Array.IO | |
import Data.Array.Base | |
import Data.Char (ord) | |
import Data.Word | |
import qualified Data.ByteString as B | |
import qualified Data.ByteString.Char8 as C8 | |
import qualified Data.ByteString.Builder as Builder | |
import System.IO | |
type Number = Word8 | |
type Count = Int -- сколько там может быть чисел на входе?... | |
type DataArray = IOUArray Number Count | |
addToIOArray :: DataArray -> Int -> IO () | |
addToIOArray arr idx = do | |
val <- unsafeRead arr idx | |
unsafeWrite arr idx $ val + 1 | |
fillIOArray :: DataArray -> 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 :: (Number, Count) -> IO () | |
printPair (x, n) = replicateM_ (fromIntegral n) $ do | |
Builder.hPutBuilder stdout $ Builder.word8Dec x <> Builder.byteString "\n" | |
main :: IO () | |
main = do | |
k <- read <$> getLine | |
arr <- newArray (0,100) 0 :: IO DataArray | |
replicateM k $ fillIOArray arr | |
hSetBuffering stdout (BlockBuffering Nothing) | |
getAssocs arr >>= mapM_ printPair |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment