aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--challenge-079/aviral-goel/haskell/ch-1.hs16
-rw-r--r--challenge-079/aviral-goel/haskell/ch-2.hs50
2 files changed, 66 insertions, 0 deletions
diff --git a/challenge-079/aviral-goel/haskell/ch-1.hs b/challenge-079/aviral-goel/haskell/ch-1.hs
new file mode 100644
index 0000000000..2033cd3f18
--- /dev/null
+++ b/challenge-079/aviral-goel/haskell/ch-1.hs
@@ -0,0 +1,16 @@
+import System.Environment (getArgs)
+
+setBitCount :: Int -> Int
+setBitCount 0 = 0
+setBitCount x = n + setBitCount x'
+ where (x', n) = divMod x 2
+
+allSetBits :: [Int] -> Int
+allSetBits = sum . map setBitCount
+
+main :: IO ()
+main = do
+ s <- fmap head getArgs
+ let x = read s :: Int
+ let bits = allSetBits [1..x] `mod` 1000000007
+ putStrLn (show bits)
diff --git a/challenge-079/aviral-goel/haskell/ch-2.hs b/challenge-079/aviral-goel/haskell/ch-2.hs
new file mode 100644
index 0000000000..b3e4c0a9ec
--- /dev/null
+++ b/challenge-079/aviral-goel/haskell/ch-2.hs
@@ -0,0 +1,50 @@
+import Data.Void (Void)
+import Text.Megaparsec
+import Text.Megaparsec.Char
+import Text.Megaparsec.Char.Lexer (decimal)
+import System.Environment (getArgs)
+import Data.Maybe (fromMaybe)
+import Data.List (find)
+
+type Column = (Int, Int)
+
+area :: (Maybe Column, Column, Maybe Column) -> Int
+area (Nothing, _, _) = 0
+area (_, _, Nothing) = 0
+area (Just (l1, h1), (_, h2), Just (l3, h3)) = (min h1 h3 - h2) * (l3 - l1 - 1)
+
+columns :: [Int] -> [Column]
+columns xs = zip [1..] xs
+
+unique :: [Column] -> [Column]
+unique [] = []
+unique [c] = [c]
+unique (v:v':c) | snd v == snd v' = unique (v':c)
+ | otherwise = v : unique (v':c)
+
+walls :: ([Column], Column, [Column]) -> (Maybe Column, Column, Maybe Column)
+walls (as, x, bs) = (find (greater x) as, x, find (greater x) bs)
+ where greater y y' = snd y' > snd y
+
+split :: [Column] -> [([Column], Column, [Column])]
+split [] = []
+split (z:zs) = reverse $ split' [] z zs []
+ where split' as x [] ys = (as, x, []) : ys
+ split' as x (b:bs) ys = split' (x:as) b bs ((as, x, (b:bs)) : ys)
+
+trappedWater :: [Int] -> Int
+trappedWater = sum . map area . map walls . split . unique . columns
+
+type Parser = Parsec Void String
+
+parseArray :: Parser [Int]
+parseArray = char '(' *> space *> sepBy decimal (char ',' <* space) <* char ')'
+
+main :: IO ()
+main = do
+ input <- fmap concat getArgs
+ let n = do
+ xs <- parseMaybe parseArray input
+ return $ trappedWater xs
+ putStrLn $ show $ fromMaybe 0 n
+