summaryrefslogtreecommitdiff
path: root/Assignment 1/CamilStaps-assignment1.hs
blob: 6bc6a4c95a858a7e28e99fa4e816b75037434e5b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import System.Environment
import Data.String.Utils
import qualified Data.List as List

main = do
	args <- getArgs
	let input = replace " " "" (head args)
	putStrLn $ "Running frequency statistics on: " ++ input
	print $ List.reverse $ List.sort $ countfreqs input 1 []
	print $ List.reverse $ List.sort $ countfreqs input 2 []
	print $ List.reverse $ List.sort $ countfreqs input 3 []
	print $ map (`shiftN` 18) input

countfreqs :: String -> Int -> [Freq] -> [Freq]
countfreqs "" _ fl = fl
countfreqs s n fl
	| length s < n = fl
	| otherwise = countfreqs (tail s) n (freqsincr fl (take n s) [])

freqsincr :: [Freq] -> String -> [Freq] -> [Freq]
freqsincr [] s fl = fl ++ [Freq { item = s, freq = 1}]
freqsincr (freq:fla) s2 flb
	| get_item freq == s2 = fla ++ flb ++ [Freq { item = s2, freq = get_freq freq + 1}]
	| otherwise = freqsincr fla s2 (flb ++ [Freq { item = get_item freq, freq = get_freq freq}])

data Freq = Freq { item :: String, freq :: Int } deriving (Eq)

get_item :: Freq -> String
get_item = item

get_freq :: Freq -> Int
get_freq = freq

instance Ord Freq where
	f1 `compare` f2 = get_freq f1 `compare` get_freq f2

instance Show Freq where
	show f = get_item f ++ " (" ++ show (get_freq f) ++ "x)"

shiftN :: Char -> Int -> Char
shiftN c 0 = c
shiftN 'Z' i = shiftN 'A' (i-1)
shiftN c i = shiftN (toEnum ((fromEnum c) + 1)) (i-1)