Solutions for the 2021 edition of Advent of Code.
This year, I try to do this in Rust ๐ฆ. I discover the language, so do not take this as an idiomatic implementation.
What I learned:
- Day01
- organization of the project
- using the
lib.rsto expose modules - referencing them in
main.rs. - Read a file with
fs::read_to_string, - iterate the lines with
.lines(). parse().unwrap()for a quick parsing of the line based on declared type in the function.
- Day02
- I used
split_whitespace, butsplit_once(" ")would have been better, because I could unpack the result directly. - If you iter a borrowed vector, you get a double reference for arguments. You can
unpack them with
for &(x, y)to access the value as (here)&str, otherwise you get&&refand you cannot compare those to string literals. Another solution is to usex.as_ref.
- I used
- Day03
- HashMap default value:
hashmap.get(x).unwrap_or(0) - HashMap mutating with default value:
hashmap.entry(w).or_insert(0) += 1
- HashMap default value:
- Day04
- Converting a
Vecinto an array withtry_into().unwrap().
- Converting a
- Day08
- Regex with the
regexcrate (along withlazy_staticto avoid duplicate compilation of regexes). - HashSet exists.
- Regex with the
- Day09
- Mutating a ref in a recursive function (say
fn func(&mut input)) can be called internally withfn(input),fn(&mut input)is not necessary.
- Mutating a ref in a recursive function (say
- Day10
- When building in release, integer will overflow with no warnings,
u32was not giving the right answer,u64does...
- When building in release, integer will overflow with no warnings,
- Day11
- You can use
get_muton anHashMapto get a mutable reference.
- You can use