Summary Files Commits Branches @commit @diff @stats
path: root / Year 2 / Functional Programming
diff options
context:
space:
mode:
Commit3e4a9412564187665ff1a1ffa96bbeb8c093dadd (patch)
Author
 Syndamia <kamen@syndamia.com>
2023-01-07 19:05:34 +0200
Committer
 Syndamia <kamen@syndamia.com>
2023-01-07 19:05:34 +0200
Files084149d44ae9f18b74d665180b064e6ac9709504 /Year 2/Functional Programming
uni-projects-3e4a9412564187665ff1a1ffa96bbeb8c093dadd.tar
uni-projects-3e4a9412564187665ff1a1ffa96bbeb8c093dadd.tar.gz
uni-projects-3e4a9412564187665ff1a1ffa96bbeb8c093dadd.zip
Parente3701da1f4e6d2e67c321766c0545c32014ab7b2 (diff)
[FP/HW4] Solved exercise 2
1 files changed, 43 insertions, 4 deletions
-rw-r--r--Year 2/Functional Programming/hw4.hs47
diff --git a/Year 2/Functional Programming/hw4.hs b/Year 2/Functional Programming/hw4.hs
index 8e35f4d..f548527 100644
--- a/Year 2/Functional Programming/hw4.hs
+++ b/Year 2/Functional Programming/hw4.hs
@@ -1,6 +1,7 @@
--- Задача 1
-
import Data.List
+import Data.Char
+
+-- Задача 1
subtr :: String -> String -> String
subtr a b = filter (\c -> not (c `elem` b)) a
@@ -41,13 +42,51 @@ decode i = read $ parseNumbers (getSegments $ sortBy (\s1 s2 -> compare (length
else if (seg!!2) `hasAllCharsIn` d then '9' -- ако cf се съдържа (и bd се съдържа)
else '6'
+-- Задача 2
+toBitString :: Char -> String
+toBitString c = calc (digitToInt c) 8
+ where
+ calc :: Int -> Int -> String
+ calc _ 0 = []
+ calc n p
+ | n - p >= 0 = '1' : (calc (n - p) (p `div` 2))
+ | otherwise = '0' : (calc n (p `div` 2))
+
+binaryToInt :: String -> Int
+binaryToInt b = calc b 0
+ where
+ calc [] acc = acc
+ calc b acc
+ | (head b) == '1' = calc (tail b) (acc + 2^((length b) - 1))
+ | otherwise = calc (tail b) acc
+
+versionSum :: String -> Int
+versionSum i = calc (concat (map toBitString i)) 0
+ where
+ calc [] vs = vs
+ calc p vs
+ | length p < 11 = vs
+ -- Пакет-литерал
+ | (take 3 (drop 3 p)) == "100" = calc (drop (6 + literalLength (drop 6 p) 0) p) (vs + binaryToInt (take 3 p))
+ -- Пакет-оператор
+ | otherwise = if p!!6 == '0' then calc (drop 22 p) (vs + binaryToInt (take 3 p))
+ else calc (drop 18 p) (vs + binaryToInt (take 3 p))
+
+ literalLength li acc
+ | head li == '0' = acc + 5
+ | otherwise = literalLength (drop 5 li) (acc + 5)
-- main
main :: IO()
main = do
sample <- readFile "sample.txt"
- print(sum (map (\l -> decode l) (lines sample)))
+ print(sum (map (\l -> decode l) (lines sample))) -- -> 61229
input <- readFile "input.txt"
- print(sum (map (\l -> decode l) (lines input)))
+ print(sum (map (\l -> decode l) (lines input))) -- -> 983026
+
+ print(versionSum "8A004A801A8002F478") -- -> 16
+ print(versionSum "620080001611562C8802118E34") -- -> 12
+ print(versionSum "C0015000016115A2E0802F182340") -- -> 23
+ print(versionSum "A0016C880162017C3686B18A3D4780") -- -> 31