It's the yearly occasion of AOC and i plan to take part of it and i would love if others would want to do the same.
What is advent of code?
Advent of Code is an Advent calendar of small programming puzzles for a variety of skill levels that can be solved in any programming language you like. [1]
Why do advent of code?
Well considering the planning on the game-jam it might be fitting. It's also a fun way to get coding and talking with others.
This topic
I want to share and discuss solutions with others, ofc hidden with use of "spoilers" or "details"
[spoiler]I did this and that[/spoiler]
[details="My solution to day ~"]
``<language> <- example: c, c#, python
My Code
``
[/details]
There is a leaderboard. And all languages are allowed. I don't remember how the leaderboard worked, but if i remember correctly the solution is often a code that we submit, so we don't submit any actual code.
I've been meaning to participate on these, but never had the time previous years. I may do some this year, it would be a great excuse to play with a less familiar language. Rust .... or could i be so bold as to bring out Haskell again... tempting
Oooh this sounds really cool, I'll try doing this, though I am rather incompetent at programming :P [1]
Will try in rust first as have been meaning to learn, may end up in python when I fail : [2]
Oh hell yeah I'm excited to see how badly I can do with TI BASIC[1]. Early on in the forum I floated the idea of hosting some code golf stuff but not many people were interested, maybe if this goes well I'll re-float it
ooooooh. that was our first programming language. if we do this year we're gonna do wasm again because that's a fun language to torture ourselves with :p
but more likely we're probably going to focus on our own projects for a bit - at least we're not going to prioritize doing the aoc solutions, we might get to them more slowly over the next month or so
I'll do Haskell day one. @achinti please say which other langue you would want to see me fight.
(i am not going to do a joke language)
but i got told to try Fortran so i might do that if people want to.
i have successfully updated my system
parsed a file + hello world
Part one done :D
My horrible code
parseStr :: String -> ([Int], [Int])
parseStr input = foldr parseLine ([], []) (lines input)
where
parseLine :: String -> ([Int], [Int]) -> ([Int], [Int])
parseLine ln (l1,l2) =
-- i did make use of chat gpt here
let num = map read (words ln) :: [Int]
in case num of
[x, y] -> (x: l1, y: l2)
_ -> error "Each line must contain exactly two numbers"
_zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] -- yeah i kinda don't get signatures yet
_zipWith _ [] [] = [] -- this is pretty cool i only forgot about the other two
_zipWith _ _ [] = []
_zipWith _ [] _ = []
_zipWith op (h1:xs1) (h2:xs2) = op h1 h2 : _zipWith op xs1 xs2
quicksort :: Ord a => [a] -> [a] -- this was in the tutorial but i still don't quite get the signature
quicksort [] = []
quicksort (p:xs) = (quicksort lesser) ++ [p] ++ (quicksort greater)
where
lesser = filter (< p) xs
greater = filter (>= p) xs
main = do
flInput <- readFile "input.go"
let parsedResult = parseStr flInput
-- print (quicksort (fst parsedResult))
-- print (quicksort (snd parsedResult))
let ans = map (abs) (_zipWith (-) (quicksort (fst parsedResult)) (quicksort (snd parsedResult)))
print (sum ans)
Hell yes!... Though, my gosh, Haskell is annoying to work with.
approach
Starting off very simple today.
Just sort both arrays,
Zip them together into pairs
Map each pair with a distance calculation
Sum the distances
code
solver:: ([Int], [Int]) -> Int
solver (as, bs) = let xs = (L.sort as)
ys = (L.sort bs)
pairs = zip xs ys
distances = map (\(a,b) -> abs (a-b)) pairs
in sum distances
For me, the difficulty wasn't the task... the difficulty was parsing the darn file in Haskell, which took me 20 minutes of trial and error. I've clearly not done this language enough to be comfortable. [1]
parsing the darn file in Haskell
import qualified Data.List as L
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
main = do
content <- TIO.readFile "input.txt"
print . solver . parse $ content
parse:: T.Text -> ([Int],[Int])
parse d = let rows = T.split (=='\n') d --- Get all rows from file
rows_split = map (T.words) rows --- split rows into word pairs
columns = L.transpose rows_split -- transpose to get columns
as = map (read . T.unpack) (columns !! 0) --- convert to integers
bs = map (read . T.unpack) (columns !! 1) --- convert to integers
in (as,bs)
Rust
It's actually Rust I really need to practice: So for now; I'll try doing both, with Rust being the priority. This actually took slighly longer because I'm more familiar with Haskell than Rust.
Summary
The exact same solution as before could quite easily be adapted to Rust, so the solution was once again quite straightforward to code. However, reading the file was no small challenge.
fn process_row(row: &str) -> Option<(i32,i32)>{
let words:Vec<&str> = row.split_whitespace().collect();
if words.len()<2{
return None
}
let v1:i32 = words[0].trim().parse().ok()?;
let v2:i32 = words[1].trim().parse().ok()?;
return Some((v1,v2))
}
fn main() {
// process file
let file_path:&str = "../input.txt";
let file = File::open(file_path).expect("failed to open file");
let reader = io::BufReader::new(file);
let rows_raw = reader.lines().filter_map(|a| a.ok());
let rows = rows_raw.filter_map(process_row);
let columns:(Vec<i32>,Vec<i32>) = rows.unzip();
// solution
let (mut list1, mut list2) = columns;
list1.sort();
list2.sort();
let pairs = list1.iter().zip(list2.iter());
let distances = pairs.map(|(a,b)| (a-b).abs());
let distance_total:i32 = distances.sum();
println!("distance total {distance_total}");
}
well i haven't even gotten to installing the compiler xD
clang us being a b###h about updating (it's mismatching llvm versions even though i handed it the correct ones)
i'm updating everything before i install a haskell compiler to avoid things breaking later.
well i still want to update my entire system before i install something.
on that note, it seems like i have compiled llvm18 with llvm19 and now llvm19 makes use of that specific llvm18
this causes issues for applications that expect things to be compiled with older versions (no idea why it causes a issue though, it's a binary)
also found more issues with xdg-portal, no idea why it refuses to give me logs but it clearly doesn't work as intended
I keep meaning to do coding stuff and don't, so maybe I'll commit to trying to do this. Unsure what language though to use as I haven't actually done much outside of just what university assigned.
Sticking with what you are comfortable with is great and if i was sane i would do the same, but i am so far gone into making my life horrible.
i still haven't managed to update my computer cause clang-18 is refuses to compile, it becomes corrupt and i frankly can't bother with it anymore. I'll have to wait for mesa to be able to run on clang-19 before i can do a sane update
Looking at your solution it's really magical.
i'll have to look up what in does, kinda seems like the opposite of where \(a, b) is weird to me too
when it comes to parsing, turns out lines and words are things - very cheating i know. Well it's base and so i didn't need imports so i am happy.
Finding out about zipWith and then finding out it was a import was fun. i though it would be harder but seeing how much haskell has i'm not terribly surprised. (i'm a bit mad about Β΄sortΒ΄, Β΄linesΒ΄, Β΄wordsΒ΄ it just seems too comfortable)
It didn't cross my mind after finding words... that lines would also exist. Obvious in retrospect.
That's just a lambda that takes a tuple. What I would question is the syntax of lambdas, which is kind of difficult to parse.
Yeah... after coming from a lot of Python where I can zip whatever I darn please, finding out zip was restricted to tuples stumped me a bit. I did get it working with transpose instead, but zipWith seems cool