Solve day 1 with Haskell

master
Alex Selimov 3 days ago
parent 72f41838cb
commit 5185e14653

@ -0,0 +1,24 @@
module Part1
( parseFileString,
quickSort,
)
where
split :: [Int] -> ([Int], [Int])
split mylist = case mylist of
[] -> ([], [])
x : xs ->
let (evens, odds) = split xs
in (x : odds, evens)
parseFileString :: String -> ([Int], [Int])
parseFileString file_string = split parsed_word_list
where
parsed_word_list = [read word :: Int | word <- words file_string]
quickSort :: [Int] -> [Int]
quickSort [] = []
quickSort (x : xs) = smallerSorted ++ [x] ++ biggerSorted
where
smallerSorted = quickSort [a | a <- xs, a <= x]
biggerSorted = quickSort [a | a <- xs, a > x]

@ -0,0 +1,16 @@
module Part2 where
import Data.Map qualified as Map
getValueCounts :: [Int] -> Map.Map Int Int
getValueCounts [] = Map.empty
getValueCounts (x : xs) =
let xsMap = getValueCounts xs
newCount = Map.findWithDefault 0 x xsMap + 1
in Map.insert x newCount xsMap
getSimilarityScore :: [Int] -> Map.Map Int Int -> Int
getSimilarityScore [] map = 0
getSimilarityScore (x : xs) map = xScore + getSimilarityScore xs map
where
xScore = x * Map.findWithDefault 0 x map

@ -0,0 +1,21 @@
# Day 1
## Instructions
From this directory open a terminal and execute:
```sh
runhaskell day1.hs
```
The solution for each section will be printed to the terminal output.
## Notes
This is my first attempt at writing Haskell code.
I've always wanted to try a formal functional programming language, and I've heard of Haskell through using tools like XMonad and Pandoc.
Since I use Pandoc regularly I thought Haskell would be a useful skill to have in case I ever need to contribute.
I also am interested in the functional programming paradigm and want to adapt my thought processes to write cleaner code.
I thought day 1 would be a good day to try Haskell, and something that would've taken me 10 minutes in any programming language I know really took me a long time.
This is definitely not good, clean, idiomatic Haskell, but it is a start!

@ -0,0 +1,21 @@
import Part1
import Part2 (getSimilarityScore, getValueCounts)
import System.IO
main = do
inputs <- readFile "inputs.txt"
let (listA, listB) = parseFileString inputs
-- Solve part 1
let sortedListA = quickSort listA
let sortedListB = quickSort listB
let distances = [abs (a - b) | (a, b) <- zip sortedListA sortedListB]
let distance = sum distances
putStrLn "The solution to part 1 is: "
print distance
-- Solve part 2
let bMap = getValueCounts sortedListB
let score = getSimilarityScore sortedListA bMap
putStrLn "The solution to part 2 is: "
print score

File diff suppressed because it is too large Load Diff
Loading…
Cancel
Save