blog/assets/js/4200b1a9.3a444325.js
github-actions[bot] 34fc48031b deploy: 2fb4765b1f
2023-11-24 15:55:55 +00:00

1 line
No EOL
136 KiB
JavaScript

"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[866],{4612:e=>{e.exports=JSON.parse('{"blogPosts":[{"id":"/2023/08/02/copr","metadata":{"permalink":"/blog/2023/08/02/copr","editUrl":"https://github.com/mfocko/blog/tree/main/blog/2023-08-02-copr.md","source":"@site/blog/2023-08-02-copr.md","title":"How can Copr help with broken dependencies","description":"Copr comes to save you when maintainer doesn\'t care.","date":"2023-08-02T00:00:00.000Z","formattedDate":"August 2, 2023","tags":[{"label":"\ud83c\udfed","permalink":"/blog/tags/\ud83c\udfed"},{"label":"red-hat","permalink":"/blog/tags/red-hat"},{"label":"copr","permalink":"/blog/tags/copr"},{"label":"admin","permalink":"/blog/tags/admin"},{"label":"vps","permalink":"/blog/tags/vps"}],"readingTime":3.44,"hasTruncateMarker":true,"authors":[{"name":"Matej Focko","email":"me+blog@mfocko.xyz","title":"a.k.a. your opinionated admin","url":"https://gitlab.com/mfocko","imageURL":"https://github.com/mfocko.png","key":"mf"}],"frontMatter":{"title":"How can Copr help with broken dependencies","description":"Copr comes to save you when maintainer doesn\'t care.","date":"2023-08-02T00:00:00.000Z","authors":[{"key":"mf","title":"a.k.a. your opinionated admin"}],"tags":["\ud83c\udfed","red-hat","copr","admin","vps"]},"unlisted":false,"nextItem":{"title":"4th week of Advent of Code \'22 in Rust","permalink":"/blog/aoc-2022/4th-week"}},"content":"When you decide to run Fedora on your VPS, you might get screwed over by using\\nrandom repositories\u2026\\n\\n\x3c!--truncate--\x3e\\n\\nWhen I \u201creserved\u201d my VPS[^1] back in June \'20, I slapped Fedora on it without\\nthinking. I bet 99% of people would say that I\'m crazy for doing such thing[^2],\\n**BUT** I\'ve been using Fedora on my PCs for some time already and it felt very\\nstable and natural to just use, even for VPS.\\n\\nOne of the first things I\'ve done was setting up a mail server. You may guess\\nwhat\'s the fun part about having a mail server\u2026 Yes, it\'s all the spam you\\nreceive and only then you realize how much \u201ccrap\u201d gets filtered on free mail\\nservices. To battle this problem I chose to use\\n[rspamd](https://github.com/rspamd/rspamd) that had CentOS support, but someone\\nhad a [Copr](https://copr.fedorainfracloud.org/) repository that I used to\\ninstall it.\\n\\n## How does Copr repositories work?\\n\\nIf you have ever used Ubuntu, you might be familiar with the concept since it is\\nvery close to [PPAs](https://help.ubuntu.com/community/PPA).\\n\\ntl;dr of the whole process consists of\\n1. enabling the Copr repository, and\\n2. installing the desired package.\\n\\nSo in shell you would do\\n```\\n# dnf copr enable \u2039copr-repository\u203a\\n# dnf install \u2039package-from-the-repository\u203a\\n```\\n\\nAnd\u2026 that\'s it! Nothing else needed! Simple, right? And literally same process\\nas you would do for the PPA.\\n\\n:::tip AUR\\n\\nOn the other hand, if you are familiar with the archLinux, you definitely know\\nAUR and what it can do for you. Copr repository is pretty similar, but the\\npackages are prebuilt in Copr and Copr repositories can carry the required\\ndependencies for said packages, which simplifies the distribution, and can even\\nhelp with installing singular packages (when you just need the dependency, not\\neverything).\\n\\n:::\\n\\n## My issue\\n\\nNow you might wonder how would I use it on my VPS. It\'s rather simple, once in\\n6 months a new Fedora release comes out. And you need to upgrade to newer\\nrelease\u2026 You don\'t need to do it right away and for such setup it probably isn\'t\\neven recommended.\\n\\n:::tip\\n\\nFedora releases are supported for a year, i.e. they live 6 months till the next\\nrelease and then another 6 months till another release.\\n\\nSome people prefer to run one version \u201cbehind\u201d. If you ever decide to run it on\\nyour home server or in a similar setup, it might be a pretty good idea to\\nfollow. I\'m using the \u201clatest greatest\u201d, cause why not :smile:\\n\\nOne way or another, you still need to bump the release every six months, unless\\nyou\'d bump 2 releases at once every year, which would be a decision, since, at\\nleast I, cannot see any benefits in it\u2026 You don\'t go for \u201cstability\u201d, cause once\\na year you switch to the latest release and then, before you bump, you use one\\nyear old software, so you\'re not even using the latest.\\n\\n:::\\n\\nFast-forward 2 years in the future, new Fedora release came out (October \'22)\\nand I was doing an upgrade. Dependencies of the rspamd have been updated and\\nrspamd builds in Copr have failed and no one fixed it. Cool, so now I can\\nupgrade, but can either ignore the dependencies or uninstall the rspamd\u2026\\n\\n## How can Copr help?\\n\\nI have managed to find\\n[specfile](https://github.com/rspamd/rspamd/blob/master/rpm/rspamd.spec) for the\\nrspamd package that they use for CentOS. There were some files apart from the\\nspecfile, so I had to make an SRPM locally and then\u2026 I just uploaded the SRPM\\nto the Copr to\\n[build](https://copr.fedorainfracloud.org/coprs/mfocko/rspamd/build/5046567/)\\nan RPM.\\n\\nI have switched the previous Copr repository for rspamd with my own and happily\\nproceeded with the upgrade.\\n\\n## Conclusion\\n\\nCopr is heavily used for testing builds on the upstream with\\n[Packit](https://packit.dev). However, as you can see, it is possible to use it\\n**very well** for packaging your own stuff and avoiding issues (such as the one\\nI have described above), if need be.\\n\\n[^1]: [vpsFree.cz](https://vpsfree.cz)\\n[^2]: Even though I\'ve been running archLinux on some Raspberry Pi\'s and also\\n on one of my \u201chome servers\u201d, before getting the VPS. You could say I like\\n to live on the edge\u2026"},{"id":"aoc-2022/4th-week","metadata":{"permalink":"/blog/aoc-2022/4th-week","editUrl":"https://github.com/mfocko/blog/tree/main/blog/aoc-2022/04-week-4.md","source":"@site/blog/aoc-2022/04-week-4.md","title":"4th week of Advent of Code \'22 in Rust","description":"Surviving fourth week in Rust.","date":"2023-07-07T15:14:00.000Z","formattedDate":"July 7, 2023","tags":[{"label":"advent-of-code","permalink":"/blog/tags/advent-of-code"},{"label":"advent-of-code-2022","permalink":"/blog/tags/advent-of-code-2022"},{"label":"rust","permalink":"/blog/tags/rust"}],"readingTime":15.175,"hasTruncateMarker":true,"authors":[{"name":"Matej Focko","email":"me+blog@mfocko.xyz","title":"a.k.a. @mf","url":"https://gitlab.com/mfocko","imageURL":"https://github.com/mfocko.png","key":"mf"}],"frontMatter":{"title":"4th week of Advent of Code \'22 in Rust","description":"Surviving fourth week in Rust.","date":"2023-07-07T15:14","slug":"aoc-2022/4th-week","authors":"mf","tags":["advent-of-code","advent-of-code-2022","rust"],"hide_table_of_contents":false},"unlisted":false,"prevItem":{"title":"How can Copr help with broken dependencies","permalink":"/blog/2023/08/02/copr"},"nextItem":{"title":"3rd week of Advent of Code \'22 in Rust","permalink":"/blog/aoc-2022/3rd-week"}},"content":"Let\'s go through the fourth week of [_Advent of Code_] in Rust.\\n\\n\x3c!--truncate--\x3e\\n\\n## [Day 22: Monkey Map](https://adventofcode.com/2022/day/22)\\n\\n:::info tl;dr\\n\\nSimulating a movement on a 2D map with given instructions. Map becomes a cube in\\nthe 2nd part\u2026\\n\\n:::\\n\\n:::caution Rant\\n\\nThis was the most obnoxious problem of this year\u2026 and a lot of Rust issues have\\nbeen hit.\\n\\n:::\\n\\n### Solution\\n\\nIt seems like a very simple problem to solve, but with very obnoxious changes in\\nthe 2nd part and also it\'s relatively hard to decompose \xbbproperly\xab.\\n\\n#### Column iterator\\n\\nIn the first part of the problem it was needed to know the boundaries of each\\nrow and column, since I stored them in `Vec<Vec<char>>` and padded with spaces\\nto ensure I have a rectangular 2D \u201carray\u201d. However when you wanted to go through\\neach row and column to determine the boundaries, it was very easy to do for the\\nrows (cause each row is a `Vec` element), but not for the columns, since they\\nspan multiple rows.\\n\\nFor this use case I have implemented my own _column iterator_:\\n```rust\\npub struct ColumnIterator<\'a, T> {\\n map: &\'a [Vec<T>],\\n column: usize,\\n\\n i: usize,\\n}\\n\\nimpl<\'a, T> ColumnIterator<\'a, T> {\\n pub fn new(map: &\'a [Vec<T>], column: usize) -> ColumnIterator<\'a, T> {\\n Self { map, column, i: 0 }\\n }\\n}\\n\\nimpl<\'a, T> Iterator for ColumnIterator<\'a, T> {\\n type Item = &\'a T;\\n\\n fn next(&mut self) -> Option<Self::Item> {\\n if self.i >= self.map.len() {\\n return None;\\n }\\n\\n self.i += 1;\\n Some(&self.map[self.i - 1][self.column])\\n }\\n}\\n```\\n\\nGiven this piece of an iterator, it is very easy to factor out the common\\nfunctionality between the rows and columns into:\\n```rust\\nlet mut find_boundaries = |constructor: fn(usize) -> Orientation,\\n iterator: &mut dyn Iterator<Item = &char>,\\n upper_bound,\\n i| {\\n let mut first_non_empty = iterator.enumerate().skip_while(|&(_, &c)| c == \' \');\\n let start = first_non_empty.next().unwrap().0 as isize;\\n\\n let mut last_non_empty = first_non_empty.skip_while(|&(_, &c)| c != \' \');\\n let end = last_non_empty.next().unwrap_or((upper_bound, &\'_\')).0 as isize;\\n\\n boundaries.insert(constructor(i), start..end);\\n};\\n```\\n\\nAnd then use it as such:\\n```rust\\n// construct all horizontal boundaries\\n(0..map.len()).for_each(|row| {\\n find_boundaries(\\n Orientation::horizontal,\\n &mut map[row].iter(),\\n map[row].len(),\\n row,\\n );\\n});\\n\\n// construct all vertical boundaries\\n(0..map[0].len()).for_each(|col| {\\n find_boundaries(\\n Orientation::vertical,\\n &mut ColumnIterator::new(&map, col),\\n map.len(),\\n col,\\n );\\n});\\n```\\n\\n#### Walking around the map\\n\\nOnce the 2nd part got introduced, you start to think about a way how not to\\ncopy-paste a lot of stuff (I haven\'t avoided it anyways\u2026). In this problem, I\'ve\\nchosen to introduce a trait (i.e. _interface_) for 2D and 3D walker.\\n```rust\\ntrait Wrap: Clone {\\n type State;\\n\\n // simulation\\n fn is_blocked(&self) -> bool;\\n fn step(&mut self, steps: isize);\\n fn turn_left(&mut self);\\n fn turn_right(&mut self);\\n\\n // movement\\n fn next(&self) -> (Self::State, Direction);\\n\\n // final answer\\n fn answer(&self) -> Output;\\n}\\n```\\n\\nEach walker maintains its own state and also provides the functions that are\\nused during the simulation. The \u201cpromised\u201d methods are separated into:\\n* _simulation_-related: that are used during the simulation from the `.fold()`\\n* _movement_-related: just a one method that holds most of the logic differences\\n between 2D and 3D\\n* _final answer_: which extracts the _proof of solution_ from the\\n implementation-specific walker\\n\\nBoth 2D and 3D versions borrow the original input and therefore you must\\nannotate the lifetime of it:\\n```rust\\nstruct Wrap2D<\'a> {\\n input: &\'a Input,\\n position: Position,\\n direction: Direction,\\n}\\nimpl<\'a> Wrap2D<\'a> {\\n fn new(input: &\'a Input) -> Wrap2D<\'a> {\\n// \u2026\\n```\\n\\n#### Problems\\n\\nI have used a lot of closures for this problem and once I introduced a parameter\\nthat was of unknown type (apart from the fact it implements a specific trait), I\\ngot suggested a \u201cfix\u201d for the compilation error that resulted in something that\\nwas not possible to parse, cause it, more than likely, violated the grammar.\\n\\nIn a similar fashion, I have been suggested changes that led to a code that\\ndidn\'t make sense by just looking at it (there was no need to try the changes),\\nfor example one suggested change in the closure parameter caused disapperance of\\nthe parameter name. :smile:\\n\\n#### Clippy\\n\\nI have to admit that Clippy was rather helpful here, I\'ll include two examples\\nof rather smart suggestions.\\n\\nWhen writing the parsing for this problem, the first thing I have spotted on the\\n`char` was the `.is_digit()` function that takes a radix as a parameter. Clippy\\nnoticed that I use `radix = 10` and suggested switching to `.is_ascii_digit()`\\nthat does exactly the same thing:\\n```diff\\n- .take_while(|c| c.is_digit(10))\\n+ .take_while(|c| c.is_ascii_digit())\\n```\\n\\nAnother useful suggestion appeared when working with the iterators and I wanted\\nto get the $n$-th element from it. You know the `.skip()`, you know the\\n`.next()`, just \u201cslap\u201d them together and we\'re done for :grin: Well, I got\\nsuggested to use `.nth()` that does exactly the combination of the two mentioned\\nmethods on iterators:\\n```diff\\n- match it.clone().skip(skip).next().unwrap() {\\n+ match it.clone().nth(skip).unwrap() {\\n```\\n\\n## [Day 23: Unstable Diffusion](https://adventofcode.com/2022/day/23)\\n\\n:::info tl;dr\\n\\nSimulating movement of elves around with a set of specific rules.\\n\\n:::\\n\\n### Solution\\n\\nThere\'s not much to mention since it\'s just a cellular automaton simulation\\n(even though the AoC rules for cellular automatons usually get out of hand\\n:wink:).\\n\\nAlthough I had a need to determine boundaries of the elves\' positions and ended\\nup with a nasty DRY violation. Knowing that you you\'re looking for maximum and\\nminimum that are, of course, exactly the same except for initial values and\\ncomparators, it looks like a rather simple fix, but typing in Rust is something\\nelse, right? In the end I settled for a function that computes both boundaries\\nwithout any duplication while using a closure:\\n```rust\\nfn get_bounds(positions: &Input) -> (Vector2D<isize>, Vector2D<isize>) {\\n let f = |init, cmp: &dyn Fn(isize, isize) -> isize| {\\n positions\\n .iter()\\n .fold(Vector2D::new(init, init), |acc, elf| {\\n Vector2D::new(cmp(acc.x(), elf.x()), cmp(acc.y(), elf.y()))\\n })\\n };\\n\\n (f(isize::MAX, &min::<isize>), f(isize::MIN, &max::<isize>))\\n}\\n```\\n\\nThis function returns a pair of 2D vectors that represent opposite points of the\\nbounding rectangle of all elves.\\n\\nYou might ask why would we need a closure and the answer is that `positions`\\ncannot be captured from within the nested function, only via closure. One more\\nfun fact on top of that is the type of the comparator\\n```rust\\n&dyn Fn(isize, isize) -> isize\\n```\\nOnce we remove the `dyn` keyword, compiler yells at us and also includes a way\\nhow to get a more thorough explanation of the error by running\\n\\n $ rustc --explain E0782\\n\\nwhich shows us\\n\\n Trait objects must include the `dyn` keyword.\\n \\n Erroneous code example:\\n \\n ```\\n trait Foo {}\\n fn test(arg: Box<Foo>) {} // error!\\n ```\\n \\n Trait objects are a way to call methods on types that are not known until\\n runtime but conform to some trait.\\n \\n Trait objects should be formed with `Box<dyn Foo>`, but in the code above\\n `dyn` is left off.\\n \\n This makes it harder to see that `arg` is a trait object and not a\\n simply a heap allocated type called `Foo`.\\n \\n To fix this issue, add `dyn` before the trait name.\\n \\n ```\\n trait Foo {}\\n fn test(arg: Box<dyn Foo>) {} // ok!\\n ```\\n \\n This used to be allowed before edition 2021, but is now an error.\\n\\n:::danger Rant\\n\\nNot all of the explanations are helpful though, in some cases they might be even\\nmore confusing than helpful, since they address _very simple_ use cases.\\n\\nAs you can see, even in this case there are two sides to the explanations:\\n* it explains why you need to use `dyn`, but\\n* it still mentions that trait objects need to be heap-allocated via `Box<T>`\\n that, as you can see in my snippet, **does not** apply here :smile: IMO it\'s\\n caused by the fact that we are borrowing it and therefore we don\'t need to\\n care about the size or whereabouts of it.\\n\\n:::\\n\\n:::info C++ parallel\\n\\nIf you dive into the explanation above, you can notice that the `Box<dyn Trait>`\\npattern is very helpful for using types that are not known during compile-time.\\nYou would use a very similar approach in C++ when parsing some data structure\\nfrom input (let\'s say JSON for example).\\n\\nOn the other hand, in this case, it doesn\'t really make much sense, cause you\\ncan clearly see that the types **are known** during the compile-time, which in\\nC++ could be easily resolved by templating the helper function.\\n\\n:::\\n\\n## [Day 24: Blizzard Basin](https://adventofcode.com/2022/day/24)\\n\\n:::info tl;dr\\n\\nNavigating your way through a basin with series of blizzards that move around\\nyou as you move.\\n\\n:::\\n\\n:::caution\\n\\nIt\'s second to last day and I went \u201c_bonkers_\u201d on the Rust :smile: Proceed to\\nread _Solution_ part on your own risk.\\n\\n:::\\n\\n### Solution\\n\\nYou are given a map with blizzards all over the place and you\'re supposed to\\nfind the minimum time it requires you to walk through the basin without getting\\nin any of the blizzards.\\n\\n#### Breakdown\\n\\nRelatively simple, yet a bit annoying, approach can be taken. It\'s technically\\na shortest-path algorithm implementation with some relaxation restrictions and\\nbeing able to stay on one position for some time, so each _vertex_ of the graph\\nis determined by the position on the map and the _timestamp_. I have chosen to\\nuse `Vector3D<usize>`, since `x` and `y` attributes can be used for the position\\nand, well, let\'s use `z` for a timestamp, cause why not, right? :wink:\\n\\n#### Evaluating the blizzards\\n\\n:::caution\\n\\nI think that this is the most perverted abuse of the traits in the whole 4 weeks\\nof AoC in Rust\u2026\\n\\n:::\\n\\nThe blizzards move along their respective directions in time and loop around in\\ntheir respective row/column. Each vertex holds position **and** time, so we can\\n_just_ index the basin with the vertex itself, right? Yes, we can :smiling_imp:\\n\\n:::tip Fun fact\\n\\nWhile writing this part, I\'ve recognized unnecessary verbosity in the code and\\ncleaned it up a bit. The changed version is shown here and the original was just\\nmore verbose.\\n\\n:::\\n\\nI\'ll skip the boring parts of checking bounds and entry/exit of the basin :wink:\\nWe can easily calculate positions of the blizzards using a modular arithmetics:\\n```rust\\nimpl Index<Position> for Basin {\\n type Output = char;\\n\\n fn index(&self, index: Position) -> &Self::Output {\\n // \u2039skipped boring parts\u203a\\n\\n // We need to account for the loops of the blizzards\\n let width = self.cols - 2;\\n let height = self.rows - 2;\\n\\n let blizzard_origin = |size, d, t, i| ((i - 1 + size + d * (t % size)) % size + 1) as usize;\\n [\\n (\\n index.y() as usize,\\n blizzard_origin(width, -1, index.z(), index.x()),\\n \'>\',\\n ),\\n (\\n index.y() as usize,\\n blizzard_origin(width, 1, index.z(), index.x()),\\n \'<\',\\n ),\\n (\\n blizzard_origin(height, -1, index.z(), index.y()),\\n index.x() as usize,\\n \'v\',\\n ),\\n (\\n blizzard_origin(height, 1, index.z(), index.y()),\\n index.x() as usize,\\n \'^\',\\n ),\\n ]\\n .iter()\\n .find_map(|&(y, x, direction)| {\\n if self.map[y][x] == direction {\\n Some(&self.map[y][x])\\n } else {\\n None\\n }\\n })\\n .unwrap_or(&\'.\')\\n }\\n}\\n```\\n\\nAs you can see, there is an expression for calculating the original position and\\nit\'s used multiple times, so why not take it out to a lambda, right? :wink:\\n\\nI couldn\'t get the `rustfmt` to format the `for`-loop nicely, so I\'ve just\\ndecided to go with iterating over an elements of a slice. I have used, once\\nagain, a combination of two functions (`find_map` in this case) to do 2 things\\nat once and at the end, if we haven\'t found any blizzard, we just return the\\nempty space.\\n\\nI think it\'s a very _nice_ (and naughty) way how to use the `Index` trait, don\'t\\nyou think?\\n\\n#### Shortest-path algorithm\\n\\nFor the shortest path you can choose and adjust any of the common shortest-path\\nalgorithms, in my case, I have decided to use [_A\\\\*_] instead of Dijkstra\'s\\nalgorithm, since it better reflects the _cost_ function.\\n\\n:::info Comparison of costs\\n\\nWith the Dijkstra\'s algorithm I would proceed with the `time` attribute used as\\na priority for the queue.\\n\\nWhereas with the _A\\\\*_, I have chosen to use both time and Manhattan distance\\nthat promotes vertices closer to the exit **and** with a minimum time taken.\\n\\n:::\\n\\nCost function is, of course, a closure :wink:\\n```rust\\nlet cost = |p: Position| p.z() as usize + exit.y().abs_diff(p.y()) + exit.x().abs_diff(p.x());\\n```\\n\\nAnd also for checking the possible moves from the current vertex, I have\\nimplemented, yet another, closure that yields an iterator with the next moves:\\n```rust\\nlet next_positions = |p| {\\n [(0, 0, 1), (0, -1, 1), (0, 1, 1), (-1, 0, 1), (1, 0, 1)]\\n .iter()\\n .filter_map(move |&(x, y, t)| {\\n let next_p = p + Vector3D::new(x, y, t);\\n\\n if basin[next_p] == \'.\' {\\n Some(next_p)\\n } else {\\n None\\n }\\n })\\n};\\n```\\n\\n#### Min-heap\\n\\nIn this case I had a need to use the priority queue taking the elements with the\\nlowest cost as the prioritized ones. Rust only offers you the [`BinaryHeap`] and\\nthat is a max-heap. One of the ways how to achieve a min-heap is to put the\\nelements in wrapped in a [`Reverse`] (as is even showed in the linked [docs of\\nthe `BinaryHeap`]). However the wrapping affects the type of the heap and also\\npopping the most prioritized elements yields values wrapped in the `Reverse`.\\n\\nFor this purpose I have just taken the max-heap and wrapped it as a whole in a\\nseparate structure providing just the desired methods:\\n```rust\\nuse std::cmp::{Ord, Reverse};\\nuse std::collections::BinaryHeap;\\n\\npub struct MinHeap<T> {\\n heap: BinaryHeap<Reverse<T>>,\\n}\\n\\nimpl<T: Ord> MinHeap<T> {\\n pub fn new() -> MinHeap<T> {\\n MinHeap {\\n heap: BinaryHeap::new(),\\n }\\n }\\n\\n pub fn push(&mut self, item: T) {\\n self.heap.push(Reverse(item))\\n }\\n\\n pub fn pop(&mut self) -> Option<T> {\\n self.heap.pop().map(|Reverse(x)| x)\\n }\\n}\\n\\nimpl<T: Ord> Default for MinHeap<T> {\\n fn default() -> Self {\\n Self::new()\\n }\\n}\\n```\\n\\nRest is just the algorithm implementation which is not that interesting.\\n\\n## [Day 25: Full of Hot Air](https://adventofcode.com/2022/day/25)\\n\\n:::info tl;dr\\n\\nPlaying around with a numbers in a _special_ base.\\n\\n:::\\n\\nGetting flashbacks to the _IB111 Foundations of Programming_\u2026 Very nice \u201cproblem\u201d\\nwith a rather easy solution, as the last day always seems to be.\\n\\n### Solution\\n\\nImplementing 2 functions, converting from the _SNAFU base_ and back to the _SNAFU_\\n_base_ representation. Let\'s do a bit more though! I have implemented two functions:\\n* `from_snafu`\\n* `to_snafu`\\n\\nNow it is apparent that all I do is number to string and string to number. Hmm\u2026\\nthat sounds familiar, doesn\'t it? Let\'s introduce a structure for the SNAFU numbers\\nand implement the traits that we need.\\n\\nLet\'s start with a structure:\\n```rust\\n#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]\\nstruct SNAFU {\\n value: i64,\\n}\\n```\\n\\n#### Converting from `&str`\\n\\nWe will start by implementing the `FromStr` trait that will help us parse our input.\\nThis is rather simple, I can just take the `from_snafu` function, copy-paste it\\ninto the `from_str` method and the number I get will be wrapped in `Result` and\\n`SNAFU` structure.\\n\\n#### Converting to `String`\\n\\nThis is more fun. In some cases you need to implement only one trait and others\\nare automatically implemented using that one trait. In our case, if you look in\\nthe documentation, you can see that `ToString` trait is automatically implemented\\nfor any type that implements `Display` trait.\\n\\nLet\'s implement the `Display` trait then. We should be able to use the `to_snafu`\\nfunction and just take the `self.value` from the `SNAFU` structure.\\n\\nAnd for the convenience of tests, we can also implement a rather simple `From<i64>`\\ntrait for the `SNAFU`.\\n\\n#### Adjusting the code\\n\\nAfter those changes we need to adjust the code and tests.\\n\\nParsing of the input is very easy, before we have used the lines, now we parse\\neverything:\\n```diff\\n fn parse_input<P: AsRef<Path>>(pathname: P) -> Input {\\n- file_to_lines(pathname)\\n+ file_to_structs(pathname)\\n }\\n```\\n\\nPart 1 needs to be adjusted a bit too:\\n```diff\\n fn part_1(input: &Input) -> Output {\\n- to_snafu(input.iter().map(|s| from_snafu(s)).sum())\\n+ SNAFU::from(input.iter().map(|s| s.value).sum::<i64>()).to_string()\\n }\\n```\\n\\nYou can also see that it simplifies the meaning a bit and it is more explicit than\\nthe previous versions.\\n\\nAnd for the tests:\\n```diff\\n #[test]\\n fn test_from() {\\n- for (n, s) in EXAMPLES.iter() {\\n- assert_eq!(from_snafu(s), *n);\\n+ for (&n, s) in EXAMPLES.iter() {\\n+ assert_eq!(s.parse::<SNAFU>().unwrap().value, n);\\n }\\n }\\n \\n #[test]\\n fn test_to() {\\n- for (n, s) in EXAMPLES.iter() {\\n- assert_eq!(to_snafu(*n), s.to_string());\\n+ for (&n, s) in EXAMPLES.iter() {\\n+ assert_eq!(SNAFU::from(n).to_string(), s.to_string());\\n }\\n```\\n\\n## Summary\\n\\nLet\'s wrap the whole thing up! Keeping in mind both AoC and the Rust\u2026\\n\\n![Finished advent calendar :smile:](/img/blog/aoc-2022/04-week-4/calendar.png)\\n\\n### Advent of Code\\n\\nThis year was quite fun, even though most of the solutions and posts came in\\nlater on (*cough* in \'23 *cough*). Day 22 was the most obnoxious one\u2026 And also\\nit feels like I used priority queues and tree data structures **a lot** :eyes:\\n\\n### with Rust\\n\\nI must admit that a lot of compiler warnings and errors were very useful. Even\\nthough I still found some instances where they didn\'t help at all or cause even\\nworse issues than I had. Compilation times have been addressed with the caching.\\n\\nBuilding my first tree data structure in Rust has been a very \u201cinteresting\u201d\\njourney. Being able to write a more generic BFS algorithm that allows you to not\\nduplicate code while still mantaining the desired functionality contributes to\\na very readable code.\\n\\nI am definitely much more aware of the basic things that bloated Python is\\nmissing, yet Rust has them\u2026\\n\\nUsing explicit types and writing down placeholder functions with `todo!()`\\nmacros is very pleasant, since it allows you to easily navigate the type system\\nduring the development when you don\'t even need to be sure how are you going to\\nput the smaller pieces together.\\n\\nI have used a plethora of traits and also implemented some of them to either be\\nidiomatic, or exploit the syntactic sugar they offer. Deriving the default trait\\nimplementation is also very helpful in a lot of cases, e.g. debugging output,\\ncopying, equality comparison, etc.\\n\\nI confess to touching more \u201ccursed\u201d parts of the Rust, such as macros to\\ndeclutter the copy-paste for tests or writing my own structures that need to\\ncarry a lifetime for their own fields.\\n\\ntl;dr Relatively pleasant language until you hit brick wall :wink:\\n\\n---\\n\\nSee you next year! Maybe in Rust, maybe not :upside_down_face:\\n\\n[_Advent of Code_]: https://adventofcode.com\\n[_A\\\\*_]: https://en.wikipedia.org/wiki/A*_search_algorithm\\n[`BinaryHeap`]: https://doc.rust-lang.org/std/collections/struct.BinaryHeap.html\\n[`Reverse`]: https://doc.rust-lang.org/std/cmp/struct.Reverse.html\\n[docs of the `BinaryHeap`]: https://doc.rust-lang.org/std/collections/struct.BinaryHeap.html#min-heap"},{"id":"aoc-2022/3rd-week","metadata":{"permalink":"/blog/aoc-2022/3rd-week","editUrl":"https://github.com/mfocko/blog/tree/main/blog/aoc-2022/03-week-3.md","source":"@site/blog/aoc-2022/03-week-3.md","title":"3rd week of Advent of Code \'22 in Rust","description":"Surviving third week in Rust.","date":"2023-07-06T21:00:00.000Z","formattedDate":"July 6, 2023","tags":[{"label":"advent-of-code","permalink":"/blog/tags/advent-of-code"},{"label":"advent-of-code-2022","permalink":"/blog/tags/advent-of-code-2022"},{"label":"rust","permalink":"/blog/tags/rust"}],"readingTime":11.565,"hasTruncateMarker":true,"authors":[{"name":"Matej Focko","email":"me+blog@mfocko.xyz","title":"a.k.a. @mf","url":"https://gitlab.com/mfocko","imageURL":"https://github.com/mfocko.png","key":"mf"}],"frontMatter":{"title":"3rd week of Advent of Code \'22 in Rust","description":"Surviving third week in Rust.","date":"2023-07-06T21:00","slug":"aoc-2022/3rd-week","authors":"mf","tags":["advent-of-code","advent-of-code-2022","rust"],"hide_table_of_contents":false},"unlisted":false,"prevItem":{"title":"4th week of Advent of Code \'22 in Rust","permalink":"/blog/aoc-2022/4th-week"},"nextItem":{"title":"Sort the matrix diagonally","permalink":"/blog/leetcode/sort-diagonally"}},"content":"Let\'s go through the third week of [_Advent of Code_] in Rust.\\n\\n\x3c!--truncate--\x3e\\n\\n## [Day 15: Beacon Exclusion Zone](https://adventofcode.com/2022/day/15)\\n\\n:::info tl;dr\\n\\nTriangulating a distress beacon based on the information from the sensors.\\n\\n:::\\n\\n### Solution\\n\\nRelatively easy thing to implement, no major Rust issues hit.\\n\\n## [Day 16: Proboscidea Volcanium](https://adventofcode.com/2022/day/16)\\n\\n:::info tl;dr\\n\\nFinding a max flow in a graph given some time constraints.\\n\\n:::\\n\\n### Solution\\n\\nI have used some interesting things to implement this and make it easier for me.\\n\\n#### Indexing in graph\\n\\nI have come across a situation where I needed to keep more information regarding\\nthe graph\u2026 In that case you can, of course, create a structure and keep it in,\\nbut once you have multiple members in the structure it gets harder to work with\\nsince you need to address the fields in the structure. When you work with graph,\\nyou frequently need to access the vertices and in this case it felt a lot easier\\nto implement the indexing in a graph, rather than explicitly access the\\nunderlying data structure.\\n\\nHere you can see a rather short snippet from the solution that allows you to\\n\u201cindex\u201d the graph:\\n```rust\\nimpl Index<&str> for Graph {\\n type Output = Vertex;\\n\\n fn index(&self, index: &str) -> &Self::Output {\\n &self.g[index]\\n }\\n}\\n```\\n\\n#### Cartesian product\\n\\nDuring the implementation I had to utilize Floyd-Warshall algorithm for finding\\nthe shortest path between pairs of vertices and utilized the `iproduct!` macro\\nfrom the [`itertools`]. It is a very useful higher-order function that allows\\nyou to keep the nesting of the loops at a minimum level while still maintaining\\nthe same functionality.\\n\\n#### \u201cImplementing\u201d an iterator\\n\\nFor the second part, you get to split the work between 2 actors. That way you\\ncan achieve higher efficiency of the whole process that you\'re planning, but it\\nalso makes it harder to evaluate algorithmically, since you need to check the\\ndifferent ways the work can be split.\\n\\nBeing affected by _functional programming brain damage_:tm:, I have chosen to\\ndo this part by function that returns an iterator over the possible ways:\\n```rust\\nfn pairings(\\n valves: &BTreeSet<String>,\\n) -> impl Iterator<Item = (BTreeSet<String>, BTreeSet<String>)> + \'_ {\\n let mapping = valves.iter().collect_vec();\\n\\n let max_mask = 1 << (valves.len() - 1);\\n\\n (0..max_mask).map(move |mask| {\\n let mut elephant = BTreeSet::new();\\n let mut human = BTreeSet::new();\\n\\n for (i, &v) in mapping.iter().enumerate() {\\n if (mask & (1 << i)) == 0 {\\n human.insert(v.clone());\\n } else {\\n elephant.insert(v.clone());\\n }\\n }\\n\\n (human, elephant)\\n })\\n}\\n```\\n\\n## [Day 17: Pyroclastic Flow](https://adventofcode.com/2022/day/17)\\n\\n:::info tl;dr\\n\\nSimulating an autonomous Tetris where pieces get affected by a series of jets of\\nhot gas.\\n\\n:::\\n\\n### Solution\\n\\nSimilarly to the previous day I have created some iterators :smile:\\n\\n#### Collision detection\\n\\nOnce you need to check for collisions it is very helpful to be able to just\\niterate through the positions that can actually collide with the wall or other\\npiece.\\n\\nTo get the desired behaviour, you can just compose few smaller functions:\\n```rust\\nfn occupied(shape: &[Vec<char>]) -> impl Iterator<Item = Position> + \'_ {\\n shape.iter().enumerate().flat_map(|(y, row)| {\\n row.iter().enumerate().filter_map(move |(x, c)| {\\n if c == &\'#\' {\\n Some(Vector2D::new(x as isize, y as isize))\\n } else {\\n None\\n }\\n })\\n })\\n}\\n```\\n\\nIn the end, we get relative positions which we can adjust later when given the\\nspecific positions from iterator. You can see some interesting parts in this:\\n\\n* `.enumerate()` allows us to get both the indices (coordinates) and the line\\n or, later on, the character itself,\\n* `.flat_map()` flattens the iterator, i.e. when we return another iterator,\\n they just get chained instead of iterating over iterators (which sounds pretty\\n disturbing, doesn\'t it?),\\n* and finally `.filter_map()` which is pretty similar to the \u201cbasic\u201d `.map()`\\n with a one, key, difference that it expects the items of an iterator to be\\n mapped to an `Option<T>` from which it ignores nothing (as in `None` :wink:)\\n and also unwraps the values from `Some(\u2026)`.\\n\\n#### Infinite iterator\\n\\nIn the solution we cycle through both Tetris-like shapes that fall down and the\\njets that move our pieces around. Initially I have implemented my own infinite\\niterator that just yields the indices. It is a very simple, yet powerful, piece\\nof code:\\n```rust\\nstruct InfiniteIndex {\\n size: usize,\\n i: usize,\\n}\\n\\nimpl InfiniteIndex {\\n fn new(size: usize) -> InfiniteIndex {\\n InfiniteIndex { size, i: size - 1 }\\n }\\n}\\n\\nimpl Iterator for InfiniteIndex {\\n type Item = usize;\\n\\n fn next(&mut self) -> Option<Self::Item> {\\n self.i = (self.i + 1) % self.size;\\n Some(self.i)\\n }\\n}\\n```\\n\\nHowever when I\'m looking at the code now, it doesn\'t really make much sense\u2026\\nGuess what, we can use a built-in function that is implemented on iterators for\\nthat! The function is called `.cycle()`\\n\\nOn the other hand, I am not going to switch to that function, since it would\\nintroduce an another myriad of issues caused by the fact that I create iterators\\nright away in the constructor of my structure and the iterators would borrow\\nboth the jets and shapes which would introduce a lifetime dependency into the\\nstructure.\\n\\n## [Day 18: Boiling Boulders](https://adventofcode.com/2022/day/18) \\n\\n:::info tl;dr\\n\\nLet\'s compute a surface area of some obsidian approximated via coordinates of\\ncubes.\\n\\n:::\\n\\n### Solution\\n\\nThis day is kinda interesting, because it shows how easily you can complicate the\\nproblem and also how much can you screw yourself over with the optimization and\\n\u201csmart\u201d approach.\\n\\nFor the first part you need to find the surface area of an obsidian that is\\napproximated by cubes. Now, that is a very easy thing to do, just keep the track\\nof already added cubes, and check if the newly added cube touches any face of any\\nother cube. Simple, and with a `BTreeSet` relatively efficient way to do it.\\n\\nHowever the second part lets you on a secret that there may be some surface area\\nfrom the \u201cinside\u201d too and you want to know only the one from the outside of the\\nobsidian. I have seen some solutions later, but if you check your data, you might\\nnotice that the bounding box of all the cubes isn\'t that big at all. Therefore I\\nchose to pre-construct the box beforehand, fill in the cubes and then just run a\\nBFS turning all the lava on the outside into the air. Now you just need to check\\ncubes and count how many of their faces touch the air.\\n\\n## [Day 19: Not Enough Minerals](https://adventofcode.com/2022/day/19)\\n\\n:::info tl;dr\\n\\nFinding out the best strategy for building robots to collect geodes.\\n\\n:::\\n\\n### Solution\\n\\nNot much interesting stuff to mention apart from the suggestion to never believe\\nthat the default implementation given by `derive` macro is what you want, it\\ndoesn\'t have to be. :smile:\\n\\n## [Day 20: Grove Positioning System](https://adventofcode.com/2022/day/20)\\n\\n:::info tl;dr\\n\\nShuffling around the _circular linked list_ to find the coordinates.\\n\\n:::\\n\\nNow, small rant for this day is in place. They\'ve never mentioned that coordinates\\ncan repeat and therefore the values are non-unique. This is something that did\\nnot happen in the given sample, but was present in the user input. It took \xbba lot\xab\\nto realize that this is the issue.\\n\\n### Solution\\n\\nI have tried implementing a circular linked list for this\u2026 and I have failed\\nmiserably. To be fair, I still have no clue why. It was \u201cfun\u201d to play around with\\nthe `Rc<RefCell<T>>`. In the end I failed on _wrong answer_. I have also encountered\\na rather interesting issue with `.borrow_mut()` method being used on `Rc<RefCell<T>>`.\\n\\n#### `.borrow_mut()`\\n\\nConsider the following snippet of the code (taken from the documentation):\\n```rust\\nuse std::cell::{RefCell, RefMut};\\nuse std::collections::HashMap;\\nuse std::rc::Rc;\\n// use std::borrow::BorrowMut;\\n\\nfn main() {\\n let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new()));\\n // Create a new block to limit the scope of the dynamic borrow\\n {\\n let mut map: RefMut<_> = shared_map.borrow_mut();\\n map.insert(\\"africa\\", 92388);\\n map.insert(\\"kyoto\\", 11837);\\n map.insert(\\"piccadilly\\", 11826);\\n map.insert(\\"marbles\\", 38);\\n }\\n\\n // Note that if we had not let the previous borrow of the cache fall out\\n // of scope then the subsequent borrow would cause a dynamic thread panic.\\n // This is the major hazard of using `RefCell`.\\n let total: i32 = shared_map.borrow().values().sum();\\n println!(\\"{total}\\");\\n}\\n```\\n\\nWe allocate a hash map on the heap and then in the inner block, we borrow it as\\na mutable reference, so that we can use it.\\n\\n:::note\\n\\nIt is a very primitive example for `Rc<RefCell<T>>` and mutable borrow.\\n\\n:::\\n\\nIf you uncomment the 4th line with `use std::borrow::BorrowMut;`, you cannot\\ncompile the code anymore, because of\\n```\\n Compiling playground v0.0.1 (/playground)\\nerror[E0308]: mismatched types\\n --\x3e src/main.rs:10:34\\n |\\n10 | let mut map: RefMut<_> = shared_map.borrow_mut();\\n | --------- ^^^^^^^^^^^^^^^^^^^^^^^ expected struct `RefMut`, found mutable reference\\n | |\\n | expected due to this\\n |\\n = note: expected struct `RefMut<\'_, _>`\\n found mutable reference `&mut Rc<RefCell<HashMap<_, _>>>`\\n\\nerror[E0599]: no method named `insert` found for struct `RefMut<\'_, _>` in the current scope\\n --\x3e src/main.rs:11:13\\n |\\n11 | map.insert(\\"africa\\", 92388);\\n | ^^^^^^ method not found in `RefMut<\'_, _>`\\n\\nerror[E0599]: no method named `insert` found for struct `RefMut<\'_, _>` in the current scope\\n --\x3e src/main.rs:12:13\\n |\\n12 | map.insert(\\"kyoto\\", 11837);\\n | ^^^^^^ method not found in `RefMut<\'_, _>`\\n\\nerror[E0599]: no method named `insert` found for struct `RefMut<\'_, _>` in the current scope\\n --\x3e src/main.rs:13:13\\n |\\n13 | map.insert(\\"piccadilly\\", 11826);\\n | ^^^^^^ method not found in `RefMut<\'_, _>`\\n\\nerror[E0599]: no method named `insert` found for struct `RefMut<\'_, _>` in the current scope\\n --\x3e src/main.rs:14:13\\n |\\n14 | map.insert(\\"marbles\\", 38);\\n | ^^^^^^ method not found in `RefMut<\'_, _>`\\n\\nSome errors have detailed explanations: E0308, E0599.\\nFor more information about an error, try `rustc --explain E0308`.\\nerror: could not compile `playground` due to 5 previous errors\\n```\\n\\nIt might seem **a bit** ridiculous. However, I got to a point where the compiler\\nsuggested `use std::borrow::BorrowMut;` and it resulted in breaking parts of the\\ncode that worked previously. I think it may be a good idea to go over what is\\nhappening here.\\n\\n##### `.borrow_mut()` on `Rc<RefCell<T>>`\\n\\nLet\'s consider a variable `x` of type `Rc<RefCell<T>>`. What happens when you\\ncall `.borrow_mut()` on it? We can look at the `Rc` type, and\u2026 hang on! There is\\nneither `.borrow_mut()` method or `BorrowMut` trait implemented. How can we do it\\nthen?\\n\\nLet\'s go further and we can see that `RefCell<T>` implements a `.borrow_mut()`\\nmethod. OK, but how can we call it on the `Rc<T>`? Easily! `Rc<T>` implements\\n`Deref<T>` and therefore you can call methods on `Rc<T>` objects as if they were\\n`T` objects. If we read on _`Deref` coercion_, we can see the following:\\n\\n> If `T` implements `Deref<Target = U>`, \u2026:\\n> * \u2026\\n> * `T` implicitly implements all the (immutable) methods of the type `U`.\\n\\nWhat is the requirement for the `.borrow_mut()` on `RefCell<T>`? Well, it needs\\n`&self`, so the `Deref` implements the `.borrow_mut()` for the `Rc<RefCell<T>>`.\\n\\n##### `BorrowMut` trait\\n\\nI have not been able to find a lot on this trait. My guess is that it provides a\\nmethod instead of a syntactic sugar (`&mut x`) for the mutable borrow. And also\\nit provides default implementations for the types:\\n```rust\\nimpl BorrowMut<str> for String\\n\\nimpl<T> BorrowMut<T> for &mut T\\nwhere\\n T: ?Sized,\\n\\nimpl<T> BorrowMut<T> for T\\nwhere\\n T: ?Sized,\\n\\nimpl<T, A> BorrowMut<[T]> for Vec<T, A>\\nwhere\\n A: Allocator,\\n\\nimpl<T, A> BorrowMut<T> for Box<T, A>\\nwhere\\n A: Allocator,\\n T: ?Sized,\\n\\nimpl<T, const N: usize> BorrowMut<[T]> for [T; N]\\n```\\n\\n##### Conflict\\n\\nNow the question is why did it break the code\u2026 My first take was that the type\\n`Rc<RefCell<T>>` has some _specialized_ implementation of the `.borrow_mut()` and\\nthe `use` overrides it with the default, which is true **in a sense**. However\\nthere is no _specialized_ implementation. Let\'s have a look at the trait and the\\ntype signature on the `RefCell<T>`:\\n```rust\\n// trait\\npub trait BorrowMut<Borrowed>: Borrow<Borrowed>\\nwhere\\n Borrowed: ?Sized,\\n{\\n fn borrow_mut(&mut self) -> &mut Borrowed;\\n}\\n\\n// \u2039RefCell<T>.borrow_mut()\u203a type signature\\npub fn borrow_mut(&self) -> RefMut<\'_, T>\\n```\\n\\nI think that we can definitely agree on the fact that `RefMut<\'_, T>` is not the\\n`RefCell<T>`.\\n\\n**In my opinion**, `RefCell<T>` implements a **separate** `.borrow_mut()` rather\\nthan implementing the interface, because it **cannot** satisfy the type requirements\\nof the trait.\\n\\n:::caution\\n\\nI wonder how are we expected to deal with this conflict, if and when, we need\\nboth the `.borrow_mut()` of the trait and `.borrow_mut()` of the `RefCell<T>`.\\n\\n:::\\n\\n:::tip Fun fact\\n\\nI was suggested by the compiler to do `use std::borrow::BorrowMut;` and break the\\ncode.\\n\\nSo much for the _almighty_ and _helpful_ compiler\u2026\\n\\n:::\\n\\n## [Day 21: Monkey Math](https://adventofcode.com/2022/day/21)\\n\\n:::info tl;dr\\n\\nComputing an expression tree and then also finding ideal value for a node.\\n\\n:::\\n\\n### Solution\\n\\nRelatively simple, until you get to the 2nd part where you start to practice\\na lot of the copy-paste. I have managed to sneak some perverted stuff in there\\nthough :) Let\'s go through the details.\\n\\n#### `Default` trait\\n\\nFor the first time and twice I had a need to have a default value for my types,\\nenumerations in this case. Rust offers a very nice trait[^1] that is described\\nas:\\n\\n> A trait for giving a type a useful default value.\\n\\nI guess it sums it up nicely. The more interesting part about this is the fact\\nthat you can use the _macro machinery_ to save yourself some typing. If you have\\nenumeration of which the default value doesn\'t bear any parameter, you can just\\ndo[^2]:\\n\\n```rust\\n#[derive(Default)]\\nenum Color {\\n #[default]\\n White,\\n Gray,\\n Black,\\n}\\n```\\n\\n#### Abusing negation\\n\\nIf you want to use a _unary minus_ operator on your own type, you can implement\\na `Neg` trait[^3]. I was dealing with a binary tree and needed a way how to look\\nat the other side, so I have just implemented the negation for flipping between\\nleft and right :smile:\\n\\n[^1]: [`Default`](https://doc.rust-lang.org/std/default/trait.Default.html) docs\\n[^2]: Pardon my example from the graph algorithms ;)\\n[^3]: [`Neg`](https://doc.rust-lang.org/std/ops/trait.Neg.html) docs\\n\\n[_Advent of Code_]: https://adventofcode.com\\n[`itertools`]: https://crates.io/crates/itertools\\n[this Reddit post and the comment]: https://www.reddit.com/r/adventofcode/comments/zb98pn/comment/iyq0ono"},{"id":"leetcode/sort-diagonally","metadata":{"permalink":"/blog/leetcode/sort-diagonally","editUrl":"https://github.com/mfocko/blog/tree/main/blog/leetcode/sort-matrix-diagonally.md","source":"@site/blog/leetcode/sort-matrix-diagonally.md","title":"Sort the matrix diagonally","description":"Compiler assisted development.","date":"2023-03-04T23:15:00.000Z","formattedDate":"March 4, 2023","tags":[{"label":"cpp","permalink":"/blog/tags/cpp"},{"label":"leetcode","permalink":"/blog/tags/leetcode"},{"label":"iterators","permalink":"/blog/tags/iterators"}],"readingTime":16.99,"hasTruncateMarker":true,"authors":[{"name":"Matej Focko","email":"me+blog@mfocko.xyz","title":"a.k.a. @mf","url":"https://gitlab.com/mfocko","imageURL":"https://github.com/mfocko.png","key":"mf"}],"frontMatter":{"title":"Sort the matrix diagonally","description":"Compiler assisted development.","date":"2023-03-04T23:15","slug":"leetcode/sort-diagonally","authors":"mf","tags":["cpp","leetcode","iterators"],"hide_table_of_contents":false},"unlisted":false,"prevItem":{"title":"3rd week of Advent of Code \'22 in Rust","permalink":"/blog/aoc-2022/3rd-week"},"nextItem":{"title":"2nd week of Advent of Code \'22 in Rust","permalink":"/blog/aoc-2022/2nd-week"}},"content":"Let\'s try to solve one of the LeetCode challenges in easy and hard mode at the\\nsame time.\\n\\n\x3c!--truncate--\x3e\\n\\n* Link to the problem: https://leetcode.com/problems/sort-the-matrix-diagonally/\\n\\n## Problem description\\n\\nA **matrix diagonal** is a diagonal line of cells starting from some cell in\\neither the topmost row or leftmost column and going in the bottom-right direction\\nuntil reaching the matrix\'s end. For example, the **matrix diagonal** starting\\nfrom `mat[2][0]`, where `mat` is a `6 x 3` matrix, includes cells `mat[2][0]`,\\n`mat[3][1]`, and `mat[4][2]`.\\n\\nGiven an `m x n` matrix `mat` of integers, sort each matrix diagonal in ascending\\norder and return the resulting matrix.\\n\\n### Example\\n\\n![Image describing the problem](https://assets.leetcode.com/uploads/2020/01/21/1482_example_1_2.png)\\n\\n## Skeleton and initial adjustments\\n\\nWe are given the following skeleton for the C++ and the given challenge:\\n\\n```cpp\\nclass Solution {\\npublic:\\n vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {\\n \\n }\\n};\\n```\\n\\nThe task is to sort the passed matrix diagonally and then return it. First of all,\\nI don\'t like to solve this in a web browser, so we\'ll need to adjust it accordingly\\nfor running it locally. We\'ll start by including the `vector` header and using\\nfully-qualified namespaces[^1] and also adding few tests:\\n\\n```cpp\\n#include <cassert>\\n#include <vector>\\n\\nusing matrix = std::vector<std::vector<int>>;\\n\\nclass Solution {\\npublic:\\n matrix diagonalSort(matrix& mat)\\n {\\n }\\n};\\n\\nstatic void test_case_1()\\n{\\n // Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]\\n // Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]\\n\\n Solution s;\\n assert((s.diagonalSort(std::vector { std::vector { 3, 3, 1, 1 },\\n std::vector { 2, 2, 1, 2 },\\n std::vector { 1, 1, 1, 2 } })\\n == std::vector { std::vector { 1, 1, 1, 1 },\\n std::vector { 1, 2, 2, 2 },\\n std::vector { 1, 2, 3, 3 } }));\\n}\\n\\nstatic void test_case_2()\\n{\\n // Input: mat =\\n // [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]]\\n // Output:\\n // [[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]]\\n\\n Solution s;\\n assert((s.diagonalSort(std::vector { std::vector { 11, 25, 66, 1, 69, 7 },\\n std::vector { 23, 55, 17, 45, 15, 52 },\\n std::vector { 75, 31, 36, 44, 58, 8 },\\n std::vector { 22, 27, 33, 25, 68, 4 },\\n std::vector { 84, 28, 14, 11, 5, 50 } })\\n == std::vector { std::vector { 5, 17, 4, 1, 52, 7 },\\n std::vector { 11, 11, 25, 45, 8, 69 },\\n std::vector { 14, 23, 25, 44, 58, 15 },\\n std::vector { 22, 27, 31, 36, 50, 66 },\\n std::vector { 84, 28, 75, 33, 55, 68 } }));\\n}\\n\\nint main()\\n{\\n test_case_1();\\n test_case_2();\\n\\n return 0;\\n}\\n```\\n\\nWe need to return the matrix, but we\'re given a reference to the input matrix. We\\ncan easily abuse the C++ here and just switch the reference to value, this way\\nthe matrix will be copied when passed to the function, we can sort the copy and\\njust return it back. And we also get yelled by the compiler for the fact that the\\nmethod doesn\'t return anything yet, so to make it \u201cshut up\u201d we will just return\\nthe input for now:\\n\\n```diff\\n- matrix diagonalSort(matrix& mat)\\n+ matrix diagonalSort(matrix mat)\\n {\\n+ return mat;\\n }\\n```\\n\\nNow, we get the copy and we\'re good to go.\\n\\n## Na\xefve solution\\n\\nAs you may know, C++ offers a plethora of functions that can be used to your\\nadvantage, given that you know how to \u201cbend\u201d the data structures accordingly.\\n\\nWhat does that mean for us? Well, we have an `std::sort`, we can use it, right?\\nLet\'s have a look at it:\\n```cpp\\ntemplate< class RandomIt >\\nvoid sort( RandomIt first, RandomIt last );\\n```\\n\\nThis overload is more than we need. What does it do? It just sorts the elements\\nin the range `[first, last)` using `operator<` on them. We can\'t sort the whole\\nmatrix using this, but\u2026 we can sort just \xbbone\xab diagonal without doing much work\\non our end.\\n\\nWhat is the `RandomIt` type though? If we look more into the documentation, we\\ncan easily find the requirements for it and also learn that it\'s a _random access_\\n_iterator_ and allows swapping its values at the same time.\\n\\n:::tip Random access iterator\\n\\nWhat is the _random access iterator_ though? We can find it in a documentation\\nand see the following description:\\n\\n> A **LegacyRandomAccessIterator** is a [LegacyBidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator)\\n> that can be moved to point to any element in constant time.\\n\\nAfter that we can see all the requirements for it being listed. I don\'t feel like\\nreading them right now, so we will just use it and see where the compilation blows\\nup, i.e. \u201c_compiler-assisted development_\u201d[^2] if you will ;)\\n\\n:::\\n\\nNow we know that we can use `std::sort` to sort the diagonal itself, but we also\\nneed to get the diagonals somehow. I\'m rather lazy, so I\'ll just delegate it to\\nsomeone else[^3]. And that way we get\\n```cpp\\nmatrix diagonalSort(matrix mat)\\n{\\n // we iterate over the diagonals\\n for (auto d : diagonals(mat)) {\\n // and we sort each diagonal\\n std::sort(d.begin(), d.end());\\n }\\n\\n // we take the matrix by copy, so we can sort in-situ and return the copy\\n // that we sorted\\n return mat;\\n}\\n```\\n\\nThis solution looks very simple, doesn\'t it? Well, cause it is.\\nLet\'s try compiling it:\\n```\\nmatrix-sort.cpp:11:23: error: use of undeclared identifier \'diagonals\' [clang-diagnostic-error]\\n for (auto d : diagonals(mat)) {\\n ^\\nFound compiler error(s).\\nmake: *** [makefile:14: tidy] Error 1\\n```\\n\\nOK, seems about right. We haven\'t implemented the `diagonals` yet. And based on\\nwhat we\'ve written so far, we need a function or a class `diagonals` that will\\ngive us the diagonals we need.\\n\\n## Implementing the `diagonals`\\n\\nCool, so we need the function that will let us go through each and every diagonal\\nin our matrix. We use the _for-range_ loop, so whatever we get back from the\\n`diagonals` must support `.begin()` and `.end()`. Since I am a masochist, we will\\ndo such functionality for a matrix of any type, not just the `int` from the challenge.\\n\\nAs I said, we need to be able to\\n* construct the object\\n* get the beginning\\n* get the end (the \u201csentinel\u201d)\\n\\n```cpp\\ntemplate <typename T>\\nclass diagonals {\\n using matrix_t = std::vector<std::vector<T>>;\\n\\n matrix_t& _matrix;\\n\\npublic:\\n diagonals(matrix_t& m)\\n : _matrix(m)\\n {\\n }\\n diagonals_iter begin()\\n {\\n /* TODO */\\n }\\n diagonals_iter end()\\n {\\n /* TODO */\\n }\\n};\\n```\\n\\nNow we have a `diagonals` that we can use to go through the diagonals. We haven\'t\\nimplemented the core of it yet. Let\'s go through what we have for now.\\n\\nWe have a templated class with templated `T` that is used as a placeholder for any\\ntype we would store in the matrix. Because I\'m lazy, I have defined the `matrix_t`\\ntype that is a \u201cshortcut\u201d for `std::vector<std::vector<T>>`, so I don\'t have to\\ntype it out all the time. Of course, we need to store the matrix, we are given,\\nas a private attribute. And then just have the constructor and the 2 methods we\\nneed for the _for-range_.\\n\\n### Iterating over diagonals\\n\\nNow that we have an object that will allow us to iterate through the diagonals,\\nwe need to implement the iterating itself. We need to go through all of them, so\\nwe have multiple options how to do so. I have decided to start from the \u201cmain\u201d\\ndiagonal that starts at `(0, 0)` index and then proceed with the diagonals starting\\nin the first row, followed by the rest of the diagonals in the first column.\\n\\nWe need to be able to tell that we\'ve iterated through all of them, and also we\\nneed to know which diagonal is next. For that purpose we will pass the indices\\nof the first cell on the diagonal. That way we can always tell how to move forward.\\n\\nWe will start by updating the `begin` and `end` to reflect our choice accordingly.\\n\\n```cpp\\ndiagonals_iter begin() { return diagonals_iter { _matrix, 0, 0 }; }\\ndiagonals_iter end() { return diagonals_iter { _matrix, 0, _matrix.size() }; }\\n```\\n\\nFor the `begin` we return the first diagonal that starts at `(0, 0)`. And because\\nwe have decided to do the diagonals in the first column at the end, the first\\ndiagonal that is not a valid one is the one at `(0, height)`. Apart from the\\nindices, we also need to pass reference to the matrix itself.\\n\\n:::note\\n\\nYou may have noticed that we also include the diagonals that have length 1,\\nspecifically the ones at `(0, height - 1)` and `(width - 1, 0)`. We are implementing\\nan iterator that **should not** care about the way it\'s being used. Therefore, we\\ndon\'t care about the fact they don\'t need to be sorted.\\n\\n:::\\n\\nCool, let\'s leave the iterator itself to someone else, right?[^4]\\n\\n### Implementing the iterator over diagonals\\n\\nWe can start with a simple skeleton based on the information that we pass from\\nthe `diagonals`. Also to utilize the `matrix_t` and also contain implementation\\ndetails hidden away, we will put this code into the `diagonals` class.\\n\\n```cpp\\nclass diagonals_iter {\\n matrix_t& m;\\n std::size_t x;\\n std::size_t y;\\n\\npublic:\\n diagonals_iter(matrix_t& matrix, std::size_t x, std::size_t y)\\n : m(matrix)\\n , x(x)\\n , y(y)\\n {\\n }\\n};\\n```\\n\\nIn this case we will be implementing a \u201csimple\u201d forward iterator, so we don\'t\\nneed to implement a lot. Notably it will be:\\n* inequality operator (we need to know when we reach the end and have nothing to\\n iterate over)\\n* preincrementation operator (we need to be able to move around the iterable)\\n* dereference operator (we need to be able to retrieve the objects we iterate\\n over)\\n\\n```cpp\\nclass diagonals_iter {\\n matrix_t& m;\\n std::size_t x;\\n std::size_t y;\\n\\npublic:\\n diagonals_iter(matrix_t& matrix, std::size_t x, std::size_t y)\\n : m(matrix)\\n , x(x)\\n , y(y)\\n {\\n }\\n\\n bool operator!=(const diagonals_iter& rhs) const\\n {\\n // iterators are not equal if they reference different matrices, or\\n // their positions differ\\n return m != rhs.m || x != rhs.x || y != rhs.y;\\n }\\n\\n diagonals_iter& operator++()\\n {\\n if (y != 0) {\\n // iterating through diagonals down the first column\\n y++;\\n return *this;\\n }\\n\\n // iterating the diagonals along the first row\\n x++;\\n if (x == m.front().size()) {\\n // switching to diagonals in the first column\\n x = 0;\\n y++;\\n }\\n\\n return *this;\\n }\\n\\n diagonal<T> operator*() const { return diagonal { m, x, y }; }\\n};\\n```\\n\\nLet\'s go one-by-one. Inequality operator is rather simple, just compare iterator\'s\\nattributes field-by-field. If you think about it, checking inequality of two 2D\\nvectors may be a bit inefficient, therefore, we can swap around and check it as\\na last thing.\\n\\n```diff\\n- return m != rhs.m || x != rhs.x || y != rhs.y;\\n+ return x != rhs.x || y != rhs.y || m != rhs.m;\\n```\\n\\nPreincrementation is where the magic happens. If you have a better look, you can\\nsee two branches of this operation:\\n\\n1. When `y != 0` (we\'re iterating over the diagonals in the first column)\\n In this case, we just bump the row and we\'re done.\\n2. When `y == 0` (we\'re iterating over the diagonals in the first row)\\n In this case, we bump the column and check if we haven\'t gotten out of bounds,\\n i.e. the end of the first row. If we get out of the bounds, we\'re continuing\\n with the second diagonal in the first column.\\n\\nDereferencing the iterator must \u201cyield\u201d something. In our case it will be the\\ndiagonal that we want to sort. For sorting we need just the iterators that can\\nmove around said diagonal. The simplest thing, we can do, is to delegate it to\\nsomething else. In our case it will be a class called `diagonal`.\\n\\n## Implementing the `diagonal` itself\\n\\nAfter implementing the iterator over diagonals, we know that all we need to describe\\na diagonal is the matrix itself and the \u201cstart\u201d of the diagonal (row and column).\\nAnd we also know that the diagonal must provide some iterators for the `std::sort`\\nfunction. We can start with the following skeleton:\\n```cpp\\ntemplate <typename T>\\nclass diagonal {\\n using matrix_t = std::vector<std::vector<T>>;\\n\\n matrix_t& matrix;\\n std::size_t x;\\n std::size_t y;\\n\\npublic:\\n diagonal(matrix_t& matrix, std::size_t x, std::size_t y)\\n : matrix(matrix)\\n , x(x)\\n , y(y)\\n {\\n }\\n\\n diagonal_iter begin() const { return diagonal_iter { matrix, x, y }; }\\n\\n diagonal_iter end() const\\n {\\n auto max_x = matrix[y].size();\\n auto max_y = matrix.size();\\n\\n // we need to find the distance in which we get out of bounds (either in\\n // column or row)\\n auto steps = std::min(max_x - x, max_y - y);\\n\\n return diagonal_iter { matrix, x + steps, y + steps };\\n }\\n};\\n```\\n\\nInitialization is rather simple, we just \u201ckeep\u201d the stuff we get, `begin` is the\\nsimplest, we just delegate.\\n\\nIn case of the `end`, it gets more complicated. We need to know where is the \u201cend\u201d\\nof the diagonal. Since `end` should point to the first element \u201cafter\u201d the iterable,\\nwe know that it\'s the first position of the iterator where either `y` becomes\\n`matrix.size()` or `x` becomes `matrix[y].size()`. Also we are moving along diagonal,\\nduh, therefore we can deduce the first \u201cposition\u201d afterwards by minimal amount of\\nsteps to get out of the any column or row, hence `std::min(max_x - x, max_y - y)`.\\nFinal position is then computed simply by adding the steps to the beginning of\\nthe diagonal.\\n\\nNow we just need to finish the iterator for the diagonal itself and we\'re done.\\n\\n### Implementing `diagonal_iter`\\n\\nThis part is the hardest from all we need to do. It\'s because of the requirements\\nof the `std::sort` that requires us to implement a _random access iterator_. I have\\nbriefly described it above, and \u201cin a nutshell\u201d it means that we need to implement\\nan iterator that can move in constant time along the diagonal in any amount of\\nsteps.\\n\\nLet\'s go through all of the functionality that our iterator needs to support to\\nbe used in `std::sort`. We need the usual operations like:\\n\\n* equality/inequality\\n* incrementation\\n* dereferencing\\n\\nWe will also add all the types that our iterator uses with the category of the\\niterator, i.e. what interface it supports:\\n```cpp\\nclass diagonal_iter {\\n // we need to keep reference to the matrix itself\\n matrix_t& m;\\n\\n // we need to be able to tell our current position\\n std::size_t x;\\n std::size_t y;\\n\\npublic:\\n using difference_type = std::ptrdiff_t;\\n using value_type = T;\\n using pointer = T*;\\n using reference = T&;\\n using iterator_category = std::random_access_iterator_tag;\\n\\n diagonal_iter(matrix_t& matrix,\\n std::size_t x,\\n std::size_t y)\\n : m(matrix)\\n , x(x)\\n , y(y)\\n {\\n }\\n\\n bool operator==(const diagonal_iter& rhs) const\\n {\\n return x == rhs.x && y == rhs.y && m == rhs.m;\\n }\\n\\n diagonal_iter& operator++()\\n {\\n // we are moving along the diagonal, so we increment both \u2039x\u203a and \u2039y\u203a at\\n // the same time\\n x++;\\n y++;\\n return *this;\\n }\\n\\n reference operator*() const { return m[y][x]; }\\n};\\n```\\n\\nThis is pretty similar to the previous iterator, but now we need to implement the\\nremaining requirements of the _random access iterator_. Let\'s see what those are:\\n\\n* decrementation - cause we need to be able to move backwards too, since _random _\\n _access iterator_ extends the interface of _bidirectional iterator_\\n* moving the iterator in either direction by steps given as an integer\\n* being able to tell the distance between two iterators\\n* define an ordering on the iterators\\n\\nLet\'s fill them in:\\n```cpp\\nclass diagonal_iter {\\n // we need to keep reference to the matrix itself\\n matrix_t& m;\\n\\n // we need to be able to tell our current position\\n std::size_t x;\\n std::size_t y;\\n\\npublic:\\n using difference_type = std::ptrdiff_t;\\n using value_type = T;\\n using pointer = T*;\\n using reference = T&;\\n using iterator_category = std::random_access_iterator_tag;\\n\\n diagonal_iter(matrix_t& matrix,\\n std::size_t x,\\n std::size_t y)\\n : m(matrix)\\n , x(x)\\n , y(y)\\n {\\n }\\n\\n bool operator==(const diagonal_iter& rhs) const\\n {\\n return x == rhs.x && y == rhs.y && m == rhs.m;\\n }\\n\\n diagonal_iter& operator++()\\n {\\n // we are moving along the diagonal, so we increment both \u2039x\u203a and \u2039y\u203a at\\n // the same time\\n x++;\\n y++;\\n return *this;\\n }\\n\\n reference operator*() const { return m[y][x]; }\\n\\n // exactly opposite to the incrementation\\n diagonal_iter operator--()\\n {\\n x--;\\n y--;\\n return *this;\\n }\\n\\n // moving \u2039n\u203a steps back is same as calling decrementation \u2039n\u203a-times, so we\\n // can just return a new iterator and subtract \u2039n\u203a from both coordinates in\\n // the matrix\\n diagonal_iter operator-(difference_type n) const\\n {\\n return diagonal_iter { m, x - n, y - n };\\n }\\n\\n // here we assume that we are given two iterators on the same diagonal\\n difference_type operator-(const diagonal_iter& rhs) const\\n {\\n assert(m == rhs.m);\\n return x - rhs.x;\\n }\\n\\n // counterpart of moving \u2039n\u203a steps backwards\\n diagonal_iter operator+(difference_type n) const\\n {\\n return diagonal_iter { m, x + n, y + n };\\n }\\n\\n // we compare the coordinates, and also assume that those 2 iterators are\\n // lying on the same diagonal\\n bool operator<(const diagonal_iter& rhs) const\\n {\\n assert(m == rhs.m);\\n return x < rhs.x && y < rhs.y;\\n }\\n};\\n```\\n\\nAt this point we could probably try and compile it, right? If we do so, we will\\nget yelled at by a compiler for the following reasons:\\n```\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1792:11: error: object of type \'diagonal<int>::diagonal_iter\' cannot be assigned because its copy assignment operator is implicitly deleted [clang-diagnostic-error]\\n __last = __next;\\n ^\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1817:11: note: in instantiation of function template specialization \'std::__unguarded_linear_insert<diagonal<int>::diagonal_iter, __gnu_cxx::__ops::_Val_less_iter>\' requested here\\n std::__unguarded_linear_insert(__i,\\n ^\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1849:9: note: in instantiation of function template specialization \'std::__insertion_sort<diagonal<int>::diagonal_iter, __gnu_cxx::__ops::_Iter_less_iter>\' requested here\\n std::__insertion_sort(__first, __first + int(_S_threshold), __comp);\\n ^\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1940:9: note: in instantiation of function template specialization \'std::__final_insertion_sort<diagonal<int>::diagonal_iter, __gnu_cxx::__ops::_Iter_less_iter>\' requested here\\n std::__final_insertion_sort(__first, __last, __comp);\\n ^\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:4820:12: note: in instantiation of function template specialization \'std::__sort<diagonal<int>::diagonal_iter, __gnu_cxx::__ops::_Iter_less_iter>\' requested here\\n std::__sort(__first, __last, __gnu_cxx::__ops::__iter_less_iter());\\n ^\\nmatrix-sort.cpp:161:18: note: in instantiation of function template specialization \'std::sort<diagonal<int>::diagonal_iter>\' requested here\\n std::sort(d.begin(), d.end());\\n ^\\nmatrix-sort.cpp:17:19: note: copy assignment operator of \'diagonal_iter\' is implicitly deleted because field \'m\' is of reference type \'diagonal<int>::matrix_t &\' (aka \'vector<std::vector<int>> &\')\\n matrix_t& m;\\n ^\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1830:2: error: no matching function for call to \'__unguarded_linear_insert\' [clang-diagnostic-error]\\n std::__unguarded_linear_insert(__i,\\n ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1850:9: note: in instantiation of function template specialization \'std::__unguarded_insertion_sort<diagonal<int>::diagonal_iter, __gnu_cxx::__ops::_Iter_less_iter>\' requested here\\n std::__unguarded_insertion_sort(__first + int(_S_threshold), __last,\\n ^\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1940:9: note: in instantiation of function template specialization \'std::__final_insertion_sort<diagonal<int>::diagonal_iter, __gnu_cxx::__ops::_Iter_less_iter>\' requested here\\n std::__final_insertion_sort(__first, __last, __comp);\\n ^\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:4820:12: note: in instantiation of function template specialization \'std::__sort<diagonal<int>::diagonal_iter, __gnu_cxx::__ops::_Iter_less_iter>\' requested here\\n std::__sort(__first, __last, __gnu_cxx::__ops::__iter_less_iter());\\n ^\\nmatrix-sort.cpp:161:18: note: in instantiation of function template specialization \'std::sort<diagonal<int>::diagonal_iter>\' requested here\\n std::sort(d.begin(), d.end());\\n ^\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1782:5: note: candidate template ignored: substitution failure [with _RandomAccessIterator = diagonal<int>::diagonal_iter, _Compare = __gnu_cxx::__ops::_Val_less_iter]\\n __unguarded_linear_insert(_RandomAccessIterator __last,\\n ^\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1923:11: error: object of type \'diagonal<int>::diagonal_iter\' cannot be assigned because its copy assignment operator is implicitly deleted [clang-diagnostic-error]\\n __last = __cut;\\n ^\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1937:9: note: in instantiation of function template specialization \'std::__introsort_loop<diagonal<int>::diagonal_iter, long, __gnu_cxx::__ops::_Iter_less_iter>\' requested here\\n std::__introsort_loop(__first, __last,\\n ^\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:4820:12: note: in instantiation of function template specialization \'std::__sort<diagonal<int>::diagonal_iter, __gnu_cxx::__ops::_Iter_less_iter>\' requested here\\n std::__sort(__first, __last, __gnu_cxx::__ops::__iter_less_iter());\\n ^\\nmatrix-sort.cpp:161:18: note: in instantiation of function template specialization \'std::sort<diagonal<int>::diagonal_iter>\' requested here\\n std::sort(d.begin(), d.end());\\n ^\\nmatrix-sort.cpp:17:19: note: copy assignment operator of \'diagonal_iter\' is implicitly deleted because field \'m\' is of reference type \'diagonal<int>::matrix_t &\' (aka \'vector<std::vector<int>> &\')\\n matrix_t& m;\\n ^\\n```\\n\\nThat\'s a lot of noise, isn\'t it? Let\'s focus on the important parts:\\n```\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1792:11: error: object of type \'diagonal<int>::diagonal_iter\' cannot be assigned because its copy assignment operator is implicitly deleted [clang-diagnostic-error]\\n\u2026\\nmatrix-sort.cpp:17:19: note: copy assignment operator of \'diagonal_iter\' is implicitly deleted because field \'m\' is of reference type \'diagonal<int>::matrix_t &\' (aka \'vector<std::vector<int>> &\')\\n matrix_t& m;\\n ^\\n```\\n\\nAh! We have a reference in our iterator, and this prevents us from having a copy\\nassignment operator (that is used \u201csomewhere\u201d in the sorting algorithm). Well\u2026\\nLet\'s just wrap it!\\n```diff\\n# we need to keep a different type than reference\\n- matrix_t& m;\\n+ std::reference_wrapper<matrix_t> m;\\n\\n# in comparison we need to get the reference out of the wrapper first\\n- return x == rhs.x && y == rhs.y && m == rhs.m;\\n+ return x == rhs.x && y == rhs.y && m.get() == rhs.m.get();\\n\\n# same when we return a reference to the \u201ccell\u201d in the matrix\\n- reference operator*() const { return m[y][x]; }\\n+ reference operator*() const { return m.get()[y][x]; }\\n\\n# and finally in the assertions that we set for the \u201cdistance\u201d and \u201cless than\u201d\\n- assert(m == rhs.m);\\n+ assert(m.get() == rhs.m.get());\\n```\\n\\nWe\'re done now! We have written an iterator over diagonals for a 2D `vector`. You can have a look at the final result [here](pathname:///files/blog/leetcode/sort-matrix-diagonally/matrix-sort.cpp).\\n\\n[^1]: just because I\'m used to it and don\'t care about your opinion ;)\\n[^2]: exercise at your own risk\\n[^3]: me in 5 minutes in fact, but don\'t make me scared\\n[^4]: me in the next section\u2026"},{"id":"aoc-2022/2nd-week","metadata":{"permalink":"/blog/aoc-2022/2nd-week","editUrl":"https://github.com/mfocko/blog/tree/main/blog/aoc-2022/02-week-2.md","source":"@site/blog/aoc-2022/02-week-2.md","title":"2nd week of Advent of Code \'22 in Rust","description":"Surviving second week in Rust.","date":"2022-12-25T23:15:00.000Z","formattedDate":"December 25, 2022","tags":[{"label":"advent-of-code","permalink":"/blog/tags/advent-of-code"},{"label":"advent-of-code-2022","permalink":"/blog/tags/advent-of-code-2022"},{"label":"rust","permalink":"/blog/tags/rust"}],"readingTime":20.875,"hasTruncateMarker":true,"authors":[{"name":"Matej Focko","email":"me+blog@mfocko.xyz","title":"a.k.a. @mf","url":"https://gitlab.com/mfocko","imageURL":"https://github.com/mfocko.png","key":"mf"}],"frontMatter":{"title":"2nd week of Advent of Code \'22 in Rust","description":"Surviving second week in Rust.","date":"2022-12-25T23:15","slug":"aoc-2022/2nd-week","authors":"mf","tags":["advent-of-code","advent-of-code-2022","rust"],"hide_table_of_contents":false},"unlisted":false,"prevItem":{"title":"Sort the matrix diagonally","permalink":"/blog/leetcode/sort-diagonally"},"nextItem":{"title":"1st week of Advent of Code \'22 in Rust","permalink":"/blog/aoc-2022/1st-week"}},"content":"Let\'s go through the second week of [_Advent of Code_] in Rust.\\n\\n\x3c!--truncate--\x3e\\n\\n## [Day 8: Treetop Tree House](https://adventofcode.com/2022/day/8)\\n\\n:::info tl;dr\\n\\nWe get a forest and we want to know how many trees are visible from the outside.\\nApart from that we want to find the best view.\\n\\n:::\\n\\nNothing interesting. We are moving around 2D map though. And indexing can get a\\nbit painful when doing so, let\'s refactor it a bit ;) During the preparation for\\nthe AoC, I have written `Vector2D` and now it\'s time to extend it with indexing\\nof `Vec` of `Vec`s. In my solution I was manipulating with indices in the following\\nway:\\n\\n- swapping them\\n- checking whether they are correct indices for the `Vec<Vec<T>>`\\n- indexing `Vec<Vec<T>>` with them\\n\\n:::caution\\n\\nI\'m getting familiar with Rust and starting to \u201cabuse\u201d it\u2026 While doing so, I\'m\\nalso uncovering some \u201cfeatures\u201d that I don\'t really like. Therefore I will mark\\nall of my rants with _thicc_ **\xab\u21af\xbb** mark and will try to \u201clock\u201d them into their\\nown \u201cbox of hell\u201d.\\n\\n:::\\n\\n#### Swapping indices\\n\\nRelatively simple implementation, just take the values, swap them and return new\\nvector.\\n\\n```rust\\nimpl<T: Copy> Vector2D<T> {\\n pub fn swap(&self) -> Self {\\n Self {\\n x: self.y,\\n y: self.x,\\n }\\n }\\n}\\n```\\n\\nPretty straight-forward implementation, but let\'s talk about the `T: Copy`. We\\nneed to use it, since we are returning a **new** vector, with swapped **values**.\\nIf we had values that cannot be copied, the only thing we could do, would be a\\nvector of references (and it would also introduce a lifetime, to which we\'ll get\\nlater on). This is pretty similar with the operations on sets from the first week.\\n\\n#### Indexing `Vec`\\n\\nI will start with the indexing, cause bound-checking is a bit more\u2026 complicated\\nthan I would like to.\\n\\n```rust\\npub fn index<\'a, T, U>(v: &\'a [Vec<U>], idx: &Vector2D<T>) -> &\'a U\\nwhere\\n usize: TryFrom<T>,\\n <usize as TryFrom<T>>::Error: Debug,\\n T: Copy,\\n{\\n let (x, y): (usize, usize) = (idx.x.try_into().unwrap(), idx.y.try_into().unwrap());\\n &v[y][x]\\n}\\n```\\n\\nLet\'s talk about this mess\u2026 Body of the function is probably the most easy part\\nand should not be hard to understand, we just take the `x` and `y` and convert\\nthem both to `usize` type that can be used later on for indexing.\\n\\nThe type signature of the function is where the fun is at :wink: We are trying\\nto convert unknown type to `usize`, so we must bound the `T` as a type that can\\nbe converted to `usize`, that\'s how we got `usize: TryFrom<T>` which basically\\nsays that `usize` must implement `TryFrom<T>` trait and therefore allows us to\\nconvert the indices to actual `usize` indices. Using `.unwrap()` also forces us\\nto bound the error that can occur when converting `T` into `usize`, that\'s how\\nwe get `<usize as TryFrom<T>>::Error: Debug` which loosely means\\n\\n> error during conversion of `T` into `usize` must implement `Debug`,\\n> i.e. can be printed in some way or other\\n\\n`T: Copy` is required by `.try_into()` which takes `T` by-value.\\n\\nAnd now we are left only with the first line of the definition.\\n\\n:::note\\n\\nSkilled Rustaceans might notice that this implementation is rather flaky and can\\nbreak in multiple places at once. I\'ll get back to it\u2026\\n\\n:::\\n\\nLet\'s split it in multiple parts:\\n- `v: &\'a [Vec<U>]` represents the 2D `Vec`, we are indexing, `Vec` implements\\n `Slice` trait and _clippy_ recommends using `&[T]` to `&Vec<T>`, exact details\\n are unknown to me\\n- `idx: &Vector2D<T>` represents the _indices_ which we use, we take them by\\n reference to avoid an unnecessary copy\\n- `-> &\'a U` means that we are returning a _reference_ to some value of type `U`.\\n Now the question is what does the `\'a` mean, we can also see it as a generic\\n type declared along `T` and `U`. And the answer is _relatively_ simple, `\'a`\\n represents a _lifetime_. We take the `v` by a reference and return a reference,\\n borrow checker validates all of the _borrows_ (or references), so we need to\\n specify that our returned value has _the same lifetime_ as the vector we have\\n taken by a reference, i.e. returned reference must live at least as long as the\\n `v`. This way we can \u201cbe sure\u201d that the returned reference is valid.\\n\\n##### Issues\\n\\nFirst issue that our implementation has is the fact that we cannot get a mutable\\nreference out of that function. This could be easily resolved by introducing new\\nfunction, e.g. `index_mut`. Which I have actually done while writing this part:\\n```rust\\npub fn index_mut<\'a, T, U>(v: &\'a mut [Vec<U>], idx: &Vector2D<T>) -> &\'a mut U\\nwhere\\n usize: TryFrom<T>,\\n <usize as TryFrom<T>>::Error: Debug,\\n T: Copy,\\n{\\n let (x, y): (usize, usize) = (idx.x.try_into().unwrap(), idx.y.try_into().unwrap());\\n &mut v[y][x]\\n}\\n```\\n\\n:::caution **\xab\u21af\xbb** Why can\'t we use one function?\\n\\nWhen we consider a `Vec<T>`, we don\'t need to consider containers as `T`, Rust\\nimplements indexing as traits `Index<T>` and `IndexMut<T>` that do the dirty work\\nbehind syntactic sugar of `container[idx]`.\\n\\nHowever, implementing of traits is not allowed for _external_ types, i.e. types\\nthat you haven\'t defined yourself. This means that you can implement indexing\\nover containers that you have implemented yourself, but you cannot use your own\\ntypes for indexing \u201cbuilt-in\u201d types.\\n\\nAnother part of this rabbit hole is trait `SliceIndex<T>` that is of a relevance\\nbecause of\\n```rust\\nimpl<T, I> Index<I> for [T]\\nwhere\\n I: SliceIndex<[T]>\\n\\nimpl<T, I, A> Index<I> for Vec<T, A>\\nwhere\\n I: SliceIndex<[T]>,\\n A: Allocator\\n\\nimpl<T, I, const N: usize> Index<I> for [T; N]\\nwhere\\n [T]: Index<I>\\n```\\n\\nIn other words, if your type implements `SliceIndex<T>` trait, it can be used\\nfor indexing. As of now, this trait has all of its required methods experimental\\nand is marked as `unsafe`.\\n\\n:::\\n\\nAnother problem is a requirement for indexing either `[Vec<T>]` or `Vec<Vec<T>>`.\\nThis requirement could be countered by removing inner type `Vec<T>` and constraining\\nit by a trait `Index` (or `IndexMut` respectively) in a following way\\n```rust\\npub fn index<\'a, C, T>(v: &\'a [C], idx: &Vector2D<T>) -> &\'a C::Output\\nwhere\\n usize: TryFrom<T>,\\n <usize as TryFrom<T>>::Error: Debug,\\n T: Copy,\\n C: Index<usize>\\n{\\n let (x, y): (usize, usize) = (idx.x.try_into().unwrap(), idx.y.try_into().unwrap());\\n &v[y][x]\\n}\\n```\\n\\nGiven this, we can also give a more meaningful typename for indexing type, such\\nas `I`.\\n\\n#### Checking bounds\\n\\nNow we can get to the boundary checks, it is very similar, but a more\u2026 dirty.\\nFirst approach that came up was to convert the indices in `Vector2D` to `usize`,\\nbut when you add the indices up, e.g. when checking the neighbors, you can end\\nup with negative values which, unlike in C++, causes an error (instead of underflow\\nthat you can use to your advantage; you can easily guess how).\\n\\nSo how can we approach this then? Well\u2026 we will convert the bounds instead of\\nthe indices and that lead us to:\\n```rust\\npub fn in_range<T, U>(v: &[Vec<U>], idx: &Vector2D<T>) -> bool\\nwhere\\n usize: TryInto<T>,\\n <usize as TryInto<T>>::Error: Debug,\\n T: PartialOrd + Copy,\\n{\\n idx.y >= 0.try_into().unwrap()\\n && idx.y < v.len().try_into().unwrap()\\n && idx.x >= 0.try_into().unwrap()\\n && idx.x\\n < v[TryInto::<usize>::try_into(idx.y).unwrap()]\\n .len()\\n .try_into()\\n .unwrap()\\n}\\n```\\n\\nYou can tell that it\'s definitely a shitty code. Let\'s improve it now! We will\\nget back to the original idea, but do it better. We know that we cannot convert\\nnegative values into `usize`, **but** we also know that conversion like that\\nreturns a `Result<T, E>` which we can use to our advantage.\\n```rust\\npub fn in_range<T, U>(v: &[Vec<U>], idx: &Vector2D<T>) -> bool\\nwhere\\n T: Copy,\\n usize: TryFrom<T>,\\n{\\n usize::try_from(idx.y)\\n .and_then(|y| usize::try_from(idx.x).map(|x| y < v.len() && x < v[y].len()))\\n .unwrap_or(false)\\n}\\n```\\n\\n`Result<T, E>` is a type similar to `Either` in Haskell and it allows us to chain\\nmultiple operations on correct results or propagate the original error without\\ndoing anything. Let\'s dissect it one-by-one.\\n\\n`try_from` is a method implemented in `TryFrom` trait, that allows you to convert\\ntypes and either successfully convert them or fail (with a reasonable error). This\\nmethod returns `Result<T, E>`.\\n\\nWe call `and_then` on that _result_, let\'s have a look at the type signature of\\n`and_then`, IMO it explains more than enough:\\n```rust\\npub fn and_then<U, F>(self, op: F) -> Result<U, E>\\nwhere\\n F: FnOnce(T) -> Result<U, E>\\n```\\n\\nOK\u2026 So it takes the result and a function and returns another result with\\ndifferent value and different error. However we can see that the function, which\\nrepresents an operation on a result, takes just the value, i.e. it doesn\'t care\\nabout any previous error. To make it short:\\n\\n> `and_then` allows us to run an operation, which can fail, on the correct result\\n\\nWe parsed a `y` index and now we try to convert the `x` index with `try_from`\\nagain, but on that result we use `map` rather than `and_then`, why would that be?\\n\\n```rust\\npub fn map<U, F>(self, op: F) -> Result<U, E>\\nwhere\\n F: FnOnce(T) -> U\\n```\\n\\nHuh\u2026 `map` performs an operation that **cannot** fail. And finally we use\\n`unwrap_or` which takes the value from result, or in case of an error returns the\\ndefault that we define.\\n\\nHow does this work then? If `y` is negative, the conversion fails and the error\\npropagates all the way to `unwrap_or`, if `y` can be a correct `usize` value, then\\nwe do the same with `x`. If `x` is negative, we propagate the error as with `y`,\\nand if it\'s not, then we check whether it exceeds the higher bounds or not.\\n\\n### Solution\\n\\nRelatively simple, you just need follow the rules and not get too smart, otherwise\\nit will get back at you.\\n\\n## [Day 9: Rope Bridge](https://adventofcode.com/2022/day/9)\\n\\n:::info tl;dr\\n\\nWe get a rope with knots and we want to track how many different positions are\\nvisited with the rope\'s tail.\\n\\n:::\\n\\nBy this day, I have come to a conclusion that current skeleton for each day\\ngenerates a lot of boilerplate. And even though it can be easily copied, it\'s\\njust a waste of space and unnecessary code. Let\'s \u201csimplify\u201d this (on one end\\nwhile creating monster on the other end). I\'ve gone through what we need in the\\npreparations for the AoC. Let\'s sum up our requirements:\\n- parsing\\n- part 1 & 2\\n- running on sample / input\\n- tests\\n\\nParsing and implementation of both parts is code that changes each day and we\\ncannot do anything about it. However running and testing can be simplified!\\n\\nLet\'s introduce and export a new module `solution` that will take care of all of\\nthis. We will start by introducing a trait for each day.\\n```rust\\npub trait Solution<Input, Output: Display> {\\n fn parse_input<P: AsRef<Path>>(pathname: P) -> Input;\\n\\n fn part_1(input: &Input) -> Output;\\n fn part_2(input: &Input) -> Output;\\n}\\n```\\n\\nThis does a lot of work for us already, we have defined a trait and for each day\\nwe will create a structure representing a specific day. That structure will also\\nimplement the `Solution` trait.\\n\\nNow we need to get rid of the boilerplate, we can\'t get rid of the `main` function,\\nbut we can at least move out the functionality.\\n```rust\\nfn run(type_of_input: &str) -> Result<()>\\nwhere\\n Self: Sized,\\n{\\n tracing_subscriber::fmt()\\n .with_env_filter(EnvFilter::from_default_env())\\n .with_target(false)\\n .with_file(true)\\n .with_line_number(true)\\n .without_time()\\n .compact()\\n .init();\\n color_eyre::install()?;\\n\\n let input = Self::parse_input(format!(\\"{}s/{}.txt\\", type_of_input, Self::day()));\\n\\n info!(\\"Part 1: {}\\", Self::part_1(&input));\\n info!(\\"Part 2: {}\\", Self::part_2(&input));\\n\\n Ok(())\\n}\\n\\nfn main() -> Result<()>\\nwhere\\n Self: Sized,\\n{\\n Self::run(\\"input\\")\\n}\\n```\\n\\nThis is all part of the `Solution` trait, which can implement methods while being\\ndependent on what is provided by the implementing types. In this case, we just\\nneed to bound the `Output` type to implement `Display` that is necessary for the\\n`info!` and format string there.\\n\\nNow we can get to first of the nasty things we are going to do\u2026 And it is the\\n`day()` method that you can see being used when constructing path to the input\\nfile. That method will generate a name of the file, e.g. `day01` and we know that\\nwe can _somehow_ deduce it from the structure name, given we name it reasonably.\\n\\n```rust\\nfn day() -> String {\\n let mut day = String::from(type_name::<Self>().split(\\"::\\").next().unwrap());\\n day.make_ascii_lowercase();\\n\\n day.to_string()\\n}\\n```\\n\\n:::caution `type_name`\\n\\nThis feature is still experimental and considered to be internal, it is not\\nadvised to use it any production code.\\n\\n:::\\n\\nAnd now we can get to the nastiest stuff :weary: We will **generate** the tests!\\n\\nWe want to be able to generate tests for sample input in a following way:\\n```rust\\ntest_sample!(day_01, Day01, 42, 69);\\n```\\n\\nThere\'s not much we can do, so we will write a macro to generate the tests for us.\\n\\n```rust\\n#[macro_export]\\nmacro_rules! test_sample {\\n ($mod_name:ident, $day_struct:tt, $part_1:expr, $part_2:expr) => {\\n #[cfg(test)]\\n mod $mod_name {\\n use super::*;\\n\\n #[test]\\n fn test_part_1() {\\n let sample =\\n $day_struct::parse_input(&format!(\\"samples/{}.txt\\", $day_struct::day()));\\n assert_eq!($day_struct::part_1(&sample), $part_1);\\n }\\n\\n #[test]\\n fn test_part_2() {\\n let sample =\\n $day_struct::parse_input(&format!(\\"samples/{}.txt\\", $day_struct::day()));\\n assert_eq!($day_struct::part_2(&sample), $part_2);\\n }\\n }\\n };\\n}\\n```\\n\\nWe have used it in a similar way as macros in C/C++, one of the things that we\\ncan use to our advantage is defining \u201ctype\u201d of the parameters for the macro. All\\nparameters have their name prefixed with `$` sign and you can define various \u201cforms\u201d\\nof your macro. Let\'s go through it!\\n\\nWe have following parameters:\\n- `$mod_name` which represents the name for the module with tests, it is typed\\n with `ident` which means that we want a valid identifier to be passed in.\\n- `$day_struct` represents the structure that will be used for tests, it is typed\\n with `tt` which represents a _token tree_, in our case it is a type.\\n- `$part_X` represents the expected output for the `X`th part and is of type `expr`\\n which literally means an _expression_.\\n\\nApart from that we need to use `#[macro_export]` to mark the macro as exported\\nfor usage outside of the module. Now our skeleton looks like:\\n```rust\\nuse aoc_2022::*;\\n\\ntype Input = String;\\ntype Output = String;\\n\\nstruct DayXX;\\nimpl Solution<Input, Output> for DayXX {\\n fn parse_input<P: AsRef<Path>>(pathname: P) -> Input {\\n file_to_string(pathname)\\n }\\n\\n fn part_1(input: &Input) -> Output {\\n todo!()\\n }\\n\\n fn part_2(input: &Input) -> Output {\\n todo!()\\n }\\n}\\n\\nfn main() -> Result<()> {\\n // DayXX::run(\\"sample\\")\\n DayXX::main()\\n}\\n\\n// test_sample!(day_XX, DayXX, , );\\n```\\n\\n### Solution\\n\\nNot much to talk about, it is relatively easy to simulate.\\n\\n## [Day 10: Cathode-Ray Tube](https://adventofcode.com/2022/day/10)\\n\\n:::info tl;dr\\n\\nEmulating basic arithmetic operations on a CPU and drawing on CRT based on the\\nCPU\'s accumulator.\\n\\n:::\\n\\nIn this day I have discovered an issue with my design of the `Solution` trait.\\nAnd the issue is caused by different types of `Output` for the part 1 and part 2.\\n\\nProblem is relatively simple and consists of simulating a CPU, I have approached\\nit in a following way:\\n```rust\\nfn evaluate_instructions(instructions: &[Instruction], mut out: Output) -> Output {\\n instructions\\n .iter()\\n .fold(State::new(), |state, instruction| {\\n state.execute(instruction, &mut out)\\n });\\n\\n out\\n}\\n```\\n\\nWe just take the instructions, we have some state of the CPU and we execute the\\ninstructions one-by-one. Perfect usage of the `fold` (or `reduce` as you may know\\nit from other languages).\\n\\nYou can also see that we have an `Output` type, so the question is how can we fix\\nthat problem. And the answer is very simple and _functional_. Rust allows you to\\nhave an `enumeration` that can _bear_ some other values apart from the type itself.\\n\\n:::tip\\n\\nWe could\'ve seen something like this with the `Result<T, E>` type that can be\\ndefined as\\n```rust\\nenum Result<T, E> {\\n Ok(T),\\n Err(E)\\n}\\n```\\n\\n###### What does that mean though?\\n\\nWhen we have an `Ok` value, it has the result itself, and when we get an `Err`\\nvalue, it has the error. This also allows us to handle _results_ in a rather\\npretty way:\\n```rust\\nmatch do_something(x) {\\n Ok(y) => {\\n println!(\\"SUCCESS: {}\\", y);\\n },\\n Err(y) => {\\n eprintln!(\\"ERROR: {}\\", y);\\n }\\n}\\n```\\n\\n:::\\n\\nMy solution has a following outline:\\n```rust\\nfn execute(&self, i: &Instruction, output: &mut Output) -> State {\\n // execute the instruction\\n\\n // collect results if necessary\\n match output {\\n Output::Part1(x) => self.execute_part_1(y, x),\\n Output::Part2(x) => self.execute_part_2(y, x),\\n }\\n\\n // return the obtained state\\n new_state\\n}\\n```\\n\\nYou might think that it\'s a perfectly reasonable thing to do. Yes, **but** notice\\nthat the `match` statement doesn\'t _collect_ the changes in any way and also we\\npass `output` by `&mut`, so it is shared across each _iteration_ of the `fold`.\\n\\nThe dirty and ingenious thing is that `x`s are passed by `&mut` too and therefore\\nthey are directly modified by the helper functions. To sum it up and let it sit\\n\\n> We are **collecting** the result **into** an **enumeration** that is **shared**\\n> across **all** iterations of `fold`.\\n\\n### Solution\\n\\nSimilar to _Day 9_, but there are some technical details that can get you.\\n\\n## [Day 11: Monkey in the Middle](https://adventofcode.com/2022/day/11)\\n\\n:::info tl;dr\\n\\nSimulation of monkeys throwing stuff around and measuring your stress levels\\nwhile your stuff is being passed around.\\n\\n:::\\n\\nI think I decided to use regular expressions here for the first time, cause\\nparsing the input was a pain.\\n\\nAlso I didn\'t expect to implement Euclidean algorithm in Rust\u2026\\n\\n### Solution\\n\\nAgain, we\'re just running a simulation. Though I must admit it was very easy to\\nmake a small technical mistakes that could affect the final results very late.\\n\\n## [Day 12: Hill Climbing Algorithm](https://adventofcode.com/2022/day/12)\\n\\n:::info tl;dr\\n\\nFinding shortest path up the hill and also shortest path down to the ground while\\nalso rolling down the hill\u2026\\n\\n:::\\n\\nAs I have said in the _tl;dr_, we are looking for the shortest path, but the start\\nand goal differ for the part 1 and 2. So I have decided to refactor my solution\\nto a BFS algorithm that takes necessary parameters via functions:\\n```rust\\nfn bfs<F, G>(\\n graph: &[Vec<char>], start: &Position, has_edge: F, is_target: G\\n) -> Option<usize>\\nwhere\\n F: Fn(&[Vec<char>], &Position, &Position) -> bool,\\n G: Fn(&[Vec<char>], &Position) -> bool\\n```\\n\\nWe pass the initial vertex from the caller and everything else is left to the BFS\\nalgorithm, based on the `has_edge` and `is_target` functions.\\n\\nThis was easy! And that is not very usual in Rust once you want to pass around\\nfunctions. :eyes:\\n\\n### Solution\\n\\nLooking for the shortest path\u2026 Must be Dijkstra, right? **Nope!** Half of the\\nReddit got jebaited though. In all fairness, nothing stops you from implementing\\nthe Dijkstra\'s algorithm for finding the shortest path, **but** if you know that\\nall connected vertices are in a unit (actually $d = 1$) distance from each other,\\nthen you know that running Dijkstra is equivalent to running BFS, only with worse\\ntime complexity, because of the priority heap instead of the queue.\\n\\n## [Day 13: Distress Signal](https://adventofcode.com/2022/day/13)\\n\\n:::info tl;dr\\n\\nProcessing packets with structured data from the distress signal.\\n\\n:::\\n\\nYou can implement a lot of traits if you want to. It is _imperative_ to implement\\nordering on the packets. I had a typo, so I also proceeded to implement a `Display`\\ntrait for debugging purposes:\\n```rust\\nimpl Display for Packet {\\n fn fmt(&self, f: &mut std::fmt::Formatter<\'_>) -> std::fmt::Result {\\n match self {\\n Packet::Integer(x) => write!(f, \\"{x}\\"),\\n Packet::List(lst) => write!(f, \\"[{}]\\", lst.iter().map(|p| format!(\\"{p}\\")).join(\\",\\")),\\n }\\n }\\n}\\n```\\n\\n### Solution\\n\\nA lot of technical details\u2026 Parsing is nasty too\u2026\\n\\n## [Day 14: Regolith Reservoir](https://adventofcode.com/2022/day/14)\\n\\n:::info tl;dr\\n\\nLet\'s simulate falling sand grain-by-grain.\\n\\n:::\\n\\nAgain, both parts are relatively similar with minimal changes, so it is a good\\nidea to refactor it a bit. Similar approach to the [BFS above]. Also this is the\\nfirst day where I ran into efficiency issues and had to redo my solution to speed\\nit up just a bit.\\n\\n### Solution\\n\\nTedious.\\n\\n## Post Mortem\\n\\n### Indexing\\n\\nI was asked about the indexing after publishing the blog. And truly it is rather\\ncomplicated topic, especially after releasing `SliceIndex<I>` trait. I couldn\'t\\nleave it be, so I tried to implement the `Index` and `IndexMut` trait.\\n\\n:::note\\n\\nI have also mentioned that the `SliceIndex` trait is `unsafe`, but truth be told,\\nonly _unsafe_ part are the 2 methods that are named `*unchecked*`. Anyways, I will\\nbe implementing the `Index*` traits for now, rather than the `SliceIndex`.\\n\\n:::\\n\\nIt\'s relatively straightforward\u2026\\n\\n```rust\\nimpl<I, C> Index<Vector2D<I>> for [C]\\nwhere\\n I: Copy + TryInto<usize>,\\n <I as TryInto<usize>>::Error: Debug,\\n C: Index<usize>,\\n{\\n type Output = C::Output;\\n\\n fn index(&self, index: Vector2D<I>) -> &Self::Output {\\n let (x, y): (usize, usize) =\\n (index.x.try_into().unwrap(), index.y.try_into().unwrap());\\n &self[y][x]\\n }\\n}\\n\\nimpl<I, C> IndexMut<Vector2D<I>> for [C]\\nwhere\\n I: Copy + TryInto<usize>,\\n <I as TryInto<usize>>::Error: Debug,\\n C: IndexMut<usize>,\\n{\\n fn index_mut(&mut self, index: Vector2D<I>) -> &mut Self::Output {\\n let (x, y): (usize, usize) =\\n (index.x.try_into().unwrap(), index.y.try_into().unwrap());\\n &mut self[y][x]\\n }\\n}\\n```\\n\\nWe can see a lot of similarities to the implementation of `index` and `index_mut`\\nfunctions. In the end, they are 1:1, just wrapped in the trait that provides a\\nsyntax sugar for `container[idx]`.\\n\\n:::note\\n\\nI have also switched from using the `TryFrom` to `TryInto` trait, since it better\\nmatches what we are using, the `.try_into` rather than `usize::try_from`.\\n\\nAlso implementing `TryFrom` automatically provides you with a `TryInto` trait,\\nsince it is relatively easy to implement. Just compare the following:\\n\\n```rust\\npub trait TryFrom<T>: Sized {\\n type Error;\\n\\n fn try_from(value: T) -> Result<Self, Self::Error>;\\n}\\n\\npub trait TryInto<T>: Sized {\\n type Error;\\n\\n fn try_into(self) -> Result<T, Self::Error>;\\n}\\n```\\n\\n:::\\n\\nOK, so we have our trait implemented, we should be able to use `container[index]`,\\nright? Yes\u2026 but actually no :frowning:\\n\\n```\\nerror[E0277]: the type `[std::vec::Vec<i8>]` cannot be indexed by `aoc_2022::Vector2D<usize>`\\n --\x3e src/bin/day08.rs:26:18\\n |\\n26 | if trees[pos] > tallest {\\n | ^^^ slice indices are of type `usize` or ranges of `usize`\\n |\\n = help: the trait `std::slice::SliceIndex<[std::vec::Vec<i8>]>` is not implemented for `aoc_2022::Vector2D<usize>`\\n = note: required for `std::vec::Vec<std::vec::Vec<i8>>` to implement `std::ops::Index<aoc_2022::Vector2D<usize>>`\\n\\nerror[E0277]: the type `[std::vec::Vec<i8>]` cannot be indexed by `aoc_2022::Vector2D<usize>`\\n --\x3e src/bin/day08.rs:30:28\\n |\\n30 | max(tallest, trees[pos])\\n | ^^^ slice indices are of type `usize` or ranges of `usize`\\n |\\n = help: the trait `std::slice::SliceIndex<[std::vec::Vec<i8>]>` is not implemented for `aoc_2022::Vector2D<usize>`\\n = note: required for `std::vec::Vec<std::vec::Vec<i8>>` to implement `std::ops::Index<aoc_2022::Vector2D<usize>>`\\n\\nerror[E0277]: the type `[std::vec::Vec<i8>]` cannot be indexed by `aoc_2022::Vector2D<isize>`\\n --\x3e src/bin/day08.rs:52:28\\n |\\n52 | let max_height = trees[position];\\n | ^^^^^^^^ slice indices are of type `usize` or ranges of `usize`\\n |\\n = help: the trait `std::slice::SliceIndex<[std::vec::Vec<i8>]>` is not implemented for `aoc_2022::Vector2D<isize>`\\n = note: required for `std::vec::Vec<std::vec::Vec<i8>>` to implement `std::ops::Index<aoc_2022::Vector2D<isize>>`\\n```\\n\\nWhy? We have it implemented for the slices (`[C]`), why doesn\'t it work? Well,\\nthe fun part consists of the fact that in other place, where we were using it,\\nwe were passing the `&[Vec<T>]`, but this is coming from a helper functions that\\ntake `&Vec<Vec<T>>` instead. And\u2026 we don\'t implement `Index` and `IndexMut` for\\nthose. Just for the slices. :exploding_head: *What are we going to do about it?*\\n\\nWe can either start copy-pasting or be smarter about it\u2026 I choose to be smarter,\\nso let\'s implement a macro! The only difference across the implementations are\\nthe types of the outer containers. Implementation doesn\'t differ **at all**!\\n\\nImplementing the macro can be done in a following way:\\n```rust\\nmacro_rules! generate_indices {\\n ($container:ty) => {\\n impl<I, C> Index<Vector2D<I>> for $container\\n where\\n I: Copy + TryInto<usize>,\\n <I as TryInto<usize>>::Error: Debug,\\n C: Index<usize>,\\n {\\n type Output = C::Output;\\n\\n fn index(&self, index: Vector2D<I>) -> &Self::Output {\\n let (x, y): (usize, usize) =\\n (index.x.try_into().unwrap(), index.y.try_into().unwrap());\\n &self[y][x]\\n }\\n }\\n\\n impl<I, C> IndexMut<Vector2D<I>> for $container\\n where\\n I: Copy + TryInto<usize>,\\n <I as TryInto<usize>>::Error: Debug,\\n C: IndexMut<usize>,\\n {\\n fn index_mut(&mut self, index: Vector2D<I>) -> &mut Self::Output {\\n let (x, y): (usize, usize) =\\n (index.x.try_into().unwrap(), index.y.try_into().unwrap());\\n &mut self[y][x]\\n }\\n }\\n };\\n}\\n```\\n\\nAnd now we can simply do\\n```rust\\ngenerate_indices!(VecDeque<C>);\\ngenerate_indices!([C]);\\ngenerate_indices!(Vec<C>);\\n// generate_indices!([C; N], const N: usize);\\n```\\n\\nThe last type (I took the inspiration from the implementations of the `Index` and\\n`IndexMut` traits) is a bit problematic, because of the `const N: usize` part,\\nwhich I haven\'t managed to be able to parse. And that\'s how I got rid of the error.\\n\\n:::note\\n\\nIf I were to use 2D-indexing over `[C; N]` slices, I\'d probably just go with the\\ncopy-paste, cause the cost of this \u201cmonstrosity\u201d outweighs the benefits of no DRY.\\n\\n:::\\n\\n#### Cause of the problem\\n\\nThis issue is relatively funny. If you don\'t use any type aliases, just the raw\\ntypes, you\'ll get suggested certain changes by the _clippy_. For example if you\\nconsider the following piece of code\\n```rust\\nfn get_sum(nums: &Vec<i32>) -> i32 {\\n nums.iter().sum()\\n}\\n\\nfn main() {\\n let nums = vec![1, 2, 3];\\n println!(\\"Sum: {}\\", get_sum(&nums));\\n}\\n```\\n\\nand you run _clippy_ on it, you will get\\n```\\nChecking playground v0.0.1 (/playground)\\nwarning: writing `&Vec` instead of `&[_]` involves a new object where a slice will do\\n --\x3e src/main.rs:1:18\\n |\\n1 | fn get_sum(nums: &Vec<i32>) -> i32 {\\n | ^^^^^^^^^ help: change this to: `&[i32]`\\n |\\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#ptr_arg\\n = note: `#[warn(clippy::ptr_arg)]` on by default\\n\\nwarning: `playground` (bin \\"playground\\") generated 1 warning\\n Finished dev [unoptimized + debuginfo] target(s) in 0.61s\\n```\\n\\nHowever, if you introduce a type alias, such as\\n```rust\\ntype Numbers = Vec<i32>;\\n```\\n\\nThen _clippy_ won\'t say anything, cause there is literally nothing to suggest.\\nHowever the outcome is not the same\u2026\\n\\n[_Advent of Code_]: https://adventofcode.com\\n[BFS above]: #day-12-hill-climbing-algorithm"},{"id":"aoc-2022/1st-week","metadata":{"permalink":"/blog/aoc-2022/1st-week","editUrl":"https://github.com/mfocko/blog/tree/main/blog/aoc-2022/01-week-1.md","source":"@site/blog/aoc-2022/01-week-1.md","title":"1st week of Advent of Code \'22 in Rust","description":"Surviving first week in Rust.","date":"2022-12-15T01:15:00.000Z","formattedDate":"December 15, 2022","tags":[{"label":"advent-of-code","permalink":"/blog/tags/advent-of-code"},{"label":"advent-of-code-2022","permalink":"/blog/tags/advent-of-code-2022"},{"label":"rust","permalink":"/blog/tags/rust"}],"readingTime":12.4,"hasTruncateMarker":true,"authors":[{"name":"Matej Focko","email":"me+blog@mfocko.xyz","title":"a.k.a. @mf","url":"https://gitlab.com/mfocko","imageURL":"https://github.com/mfocko.png","key":"mf"}],"frontMatter":{"title":"1st week of Advent of Code \'22 in Rust","description":"Surviving first week in Rust.","date":"2022-12-15T01:15","slug":"aoc-2022/1st-week","authors":"mf","tags":["advent-of-code","advent-of-code-2022","rust"],"hide_table_of_contents":false},"unlisted":false,"prevItem":{"title":"2nd week of Advent of Code \'22 in Rust","permalink":"/blog/aoc-2022/2nd-week"},"nextItem":{"title":"Advent of Code \'22 in Rust","permalink":"/blog/aoc-2022/intro"}},"content":"Let\'s go through the first week of [_Advent of Code_] in Rust.\\n\\n\x3c!--truncate--\x3e\\n\\n:::note\\n\\nIf you wish to have a look at the solutions, you can follow them on my [GitLab].\\nMore specifically in the [`/src/bin/`].\\n\\n:::\\n\\nI will try to summarize my experience with using Rust for the AoC. Trying it out\\nages ago, I believe it will be _pain and suffering_, but we will see. For each\\nday I will also try to give a tl;dr of the problem, so that you can better imagine\\nthe relation to my woes or :+1: moments.\\n\\n## [Day 1: Calorie Counting](https://adventofcode.com/2022/day/1)\\n\\n:::info tl;dr\\n\\nAs the name suggests, we get the calories of the food contained in the elves\\nbackpacks and we want to choose the elf that has the most food ;)\\n\\n:::\\n\\n> Wakey wakey!\\n\\nProgramming in Rust at 6am definitely hits. I\'ve also forgotten to mention how I\\nhandle samples. With each puzzle you usually get a sample input and expected\\noutput. You can use them to verify that your solution works, or usually doesn\'t.\\n\\nAt first I\'ve decided to put asserts into my `main`, something like\\n```rust\\nassert_eq!(part_1(&sample), 24000);\\ninfo!(\\"Part 1: {}\\", part_1(&input));\\n\\nassert_eq!(part_2(&sample), 45000);\\ninfo!(\\"Part 2: {}\\", part_2(&input));\\n```\\n\\nHowever, once you get further, the sample input may take some time to run itself.\\nSo in the end, I have decided to turn them into unit tests:\\n```rust\\n#[cfg(test)]\\nmod tests {\\n use super::*;\\n\\n #[test]\\n fn test_part_1() {\\n let sample = parse_input(\\"samples/day01.txt\\");\\n assert_eq!(part_1(&sample), 24000);\\n }\\n\\n #[test]\\n fn test_part_2() {\\n let sample = parse_input(\\"samples/day01.txt\\");\\n assert_eq!(part_2(&sample), 45000);\\n }\\n}\\n```\\n\\nAnd later on I have noticed, it\'s hard to tell the difference between the days,\\nso I further renamed the `mod` from generic `tests` to reflect the days.\\n\\nAlso after finishing the first day puzzle, I have installed an [`sccache`] to\\ncache the builds, so that the build time is lower, cause it was kinda unbearable.\\n\\n### Solution\\n\\nWell, it\'s a pretty simple problem. You just take the input, sum the calories and\\nfind the biggest one. However, if we try to generalize to more than the biggest\\none, the fun appears. We have few options:\\n\\n- keep all the calories, sort them, take what we need\\n- keep all the calories and use max heap\\n- use min heap and maintain at most N calories that we need\\n\\n## [Day 2: Rock Paper Scissors](https://adventofcode.com/2022/day/2)\\n\\n:::info tl;dr\\n\\nYou want to know what score did you achieve while playing _Rock Paper Scissors_.\\nAnd then you want to be strategic about it.\\n\\n:::\\n\\nApart from the technical details of the puzzle, it went relatively smooth.\\n\\n### Solution\\n\\nI took relatively na\xefve approach and then tried to simplify it.\\n\\n## [Day 3: Rucksack Reorganization](https://adventofcode.com/2022/day/3)\\n\\n:::info tl;dr\\n\\nLet\'s go reorganize elves\' backpacks! Each backpacks has 2 compartments and you\\nwant to find the common item among those compartments. Each of them has priority,\\nyou care only about the sum.\\n\\n:::\\n\\nThis is the day where I started to fight the compiler and neither of us decided\\nto give up. Let\'s dive into it \\\\o/\\n\\n:::tip Fun fact\\n\\nFighting the compiler took me 30 minutes.\\n\\n:::\\n\\nWe need to find a common item among 2 collections, that\'s an easy task, right?\\nWe can construct 2 sets and find an intersection:\\n```rust\\nlet top: HashSet<i32> = [1, 2, 3].iter().collect();\\nlet bottom: HashSet<i32> = [3, 4, 5].iter().collect();\\n```\\n\\nNow, the first issue that we encounter is caused by the fact that we are using\\na slice (the `[\u2026]`), iterator of that returns **references** to the numbers.\\nAnd we get immediately yelled at by the compiler, because the numbers are discarded\\nafter running the `.collect`. To fix this, we can use `.into_iter`:\\n```rust\\nlet top: HashSet<i32> = [1, 2, 3].into_iter().collect();\\nlet bottom: HashSet<i32> = [3, 4, 5].into_iter().collect();\\n```\\n\\nThis way the numbers will get copied instead of referenced. OK, let\'s find the\\nintersection of those 2 collections:\\n```rust\\nprintln!(\\"Common elements: {:?}\\", top.intersection(&bottom));\\n```\\n```\\nCommon elements: [3]\\n```\\n\\n:::caution\\n\\nNotice that we need to do `&bottom`. It explicitly specifies that `.intersection`\\n**borrows** the `bottom`, i.e. takes an immutable reference to it.\\n\\n:::\\n\\nThat\'s what we want, right? Looks like it! \\\\o/\\n\\nNext part wants us to find the common element among all of the backpacks. OK, so\\nthat should be fairly easy, we have an intersection and we want to find intersection\\nover all of them.\\n\\nLet\'s have a look at the type of the `.intersection`\\n```rust\\npub fn intersection<\'a>(\\n\xa0\xa0\xa0\xa0&\'a self,\\n\xa0\xa0\xa0\xa0other: &\'a HashSet<T, S>\\n) -> Intersection<\'a, T, S>\\n```\\n\\nOK\u2026 Huh\u2026 But we have an example there!\\n```rust\\nlet intersection: HashSet<_> = a.intersection(&b).collect();\\n```\\n\\nCool, that\'s all we need.\\n```rust\\nlet top: HashSet<i32> = [1, 2, 3, 4].into_iter().collect();\\nlet bottom: HashSet<i32> = [3, 4, 5, 6].into_iter().collect();\\nlet top_2: HashSet<i32> = [2, 3, 4, 5, 6].into_iter().collect();\\nlet bottom_2: HashSet<i32> = [4, 5, 6].into_iter().collect();\\n\\nlet intersection: HashSet<_> = top.intersection(&bottom).collect();\\nprintln!(\\"Intersection: {:?}\\", intersection);\\n```\\n```\\nIntersection: {3, 4}\\n```\\n\\nCool, so let\'s do the intersection with the `top_2`:\\n```rust\\nlet top: HashSet<i32> = [1, 2, 3, 4].into_iter().collect();\\nlet bottom: HashSet<i32> = [3, 4, 5, 6].into_iter().collect();\\nlet top_2: HashSet<i32> = [2, 3, 4, 5, 6].into_iter().collect();\\nlet bottom_2: HashSet<i32> = [4, 5, 6].into_iter().collect();\\n\\nlet intersection: HashSet<_> = top.intersection(&bottom).collect();\\nlet intersection: HashSet<_> = intersection.intersection(&top_2).collect();\\nprintln!(\\"Intersection: {:?}\\", intersection);\\n```\\n\\nAnd we get yelled at by the compiler:\\n```\\nerror[E0308]: mismatched types\\n --\x3e src/main.rs:10:58\\n |\\n10 | let intersection: HashSet<_> = intersection.intersection(&top_2).collect();\\n | ------------ ^^^^^^ expected `&i32`, found `i32`\\n | |\\n | arguments to this function are incorrect\\n |\\n = note: expected reference `&HashSet<&i32>`\\n found reference `&HashSet<i32>`\\n```\\n\\n/o\\\\ What the hell is going on here? Well, the funny thing is, that this operation\\ndoesn\'t return the elements themselves, but the references to them and when we pass\\nthe third set, it has just the values themselves, without any references.\\n\\n:::tip\\n\\nIt may seem as a very weird decision, but in fact it makes some sense\u2026 It allows\\nyou to do intersection of items that may not be possible to copy. Overall this is\\na \u201ctax\u201d for having a borrow checker ~~drilling your ass~~ having your back and\\nmaking sure you\'re not doing something naughty that may cause an **undefined**\\n**behavior**.\\n\\n:::\\n\\nTo resolve this we need to get an iterator that **clones** the elements:\\n```rust\\nlet top: HashSet<i32> = [1, 2, 3, 4].into_iter().collect();\\nlet bottom: HashSet<i32> = [3, 4, 5, 6].into_iter().collect();\\nlet top_2: HashSet<i32> = [2, 3, 4, 5, 6].into_iter().collect();\\nlet bottom_2: HashSet<i32> = [4, 5, 6].into_iter().collect();\\n\\nlet intersection: HashSet<_> = top.intersection(&bottom).cloned().collect();\\nlet intersection: HashSet<_> = intersection.intersection(&top_2).cloned().collect();\\nlet intersection: HashSet<_> = intersection.intersection(&bottom_2).cloned().collect();\\nprintln!(\\"Intersection: {:?}\\", intersection);\\n```\\n```\\nIntersection: {4}\\n```\\n\\n### Solution\\n\\nThe approach is pretty simple, if you omit the _1on1 with the compiler_. You just\\nhave some fun with the set operations :)\\n\\n## [Day 4: Camp Cleanup](https://adventofcode.com/2022/day/4)\\n\\n:::info tl;dr\\n\\nElves are cleaning up the camp and they got overlapping sections to clean up.\\nFind how many overlap and can take the day off.\\n\\n:::\\n\\n[`RangeInclusive`] is your friend not an enemy :)\\n\\n### Solution\\n\\nRelatively easy, you just need to parse the input and know what you want. Rust\'s\\n`RangeInclusive` type helped a lot, cause it took care of all abstractions.\\n\\n## [Day 5: Supply Stacks](https://adventofcode.com/2022/day/5)\\n\\n:::info tl;dr\\n\\nLet\'s play with stacks of crates.\\n\\n:::\\n\\nVery easy problem with very annoying input. You can judge yourself:\\n```\\n [D] \\n[N] [C] \\n[Z] [M] [P]\\n 1 2 3 \\n\\nmove 1 from 2 to 1\\nmove 3 from 1 to 3\\nmove 2 from 2 to 1\\nmove 1 from 1 to 2\\n```\\n\\nGood luck transforming that into something reasonable :)\\n\\n\\n:::tip Fun fact\\n\\nTook me 40 minutes to parse this reasonably, including fighting the compiler.\\n\\n:::\\n\\n### Solution\\n\\nFor the initial solution I went with a manual solution (as in _I have done all_\\n_the work_. Later on I have decided to explore the `std` and interface of the\\n`std::vec::Vec` and found [`split_off`] which takes an index and splits (duh)\\nthe vector:\\n```rust\\nlet mut vec = vec![1, 2, 3];\\nlet vec2 = vec.split_off(1);\\nassert_eq!(vec, [1]);\\nassert_eq!(vec2, [2, 3]);\\n```\\n\\nThis helped me simplify my solution a lot and also get rid of some _edge cases_.\\n\\n## [Day 6: Tuning Trouble](https://adventofcode.com/2022/day/6)\\n\\n:::info tl;dr\\n\\nFinding start of the message in a very weird protocol. Start of the message is\\ndenoted by $N$ unique consecutive characters.\\n\\n:::\\n\\n### Solution\\n\\nA lot of different approaches, knowing that we are dealing with input consisting\\nsolely of ASCII letters, I bit the bullet and went with sliding window and\\nconstructing sets from that window, checking if the set is as big as the window.\\n\\nOne possible optimization could consist of keeping a bit-vector (i.e. `usize`\\nvariable) of encountered characters and updating it as we go. However this has\\na different issue and that is removal of the characters from the left side of the\\nwindow. We don\'t know if the same character is not included later on.\\n\\nOther option is to do similar thing, but keeping the frequencies of the letters,\\nand again knowing we have only ASCII letters we can optimize by having a vector\\nof 26 elements that keeps count for each lowercase letter.\\n\\n## [Day 7: No Space Left On Device](https://adventofcode.com/2022/day/7)\\n\\n:::info tl;dr\\n\\nLet\'s simulate [`du`] to get some stats about our file system and then pinpoint\\ndirectories that take a lot of space and should be deleted.\\n\\n:::\\n\\n> I was waiting for this moment, and yet it got me!\\n> *imagine me swearing for hours*\\n\\n### Solution\\n\\nWe need to \u201c_build_\u201d a file system from the input that is given in a following form:\\n```\\n$ cd /\\n$ ls\\ndir a\\n14848514 b.txt\\n8504156 c.dat\\ndir d\\n$ cd a\\n$ ls\\ndir e\\n29116 f\\n2557 g\\n62596 h.lst\\n$ cd e\\n$ ls\\n584 i\\n$ cd ..\\n$ cd ..\\n$ cd d\\n$ ls\\n4060174 j\\n8033020 d.log\\n5626152 d.ext\\n7214296 k\\n```\\n\\nThere are few ways in which you can achieve this and also you can assume some\\npreconditions, but why would we do that, right? :)\\n\\nYou can \u201cslap\u201d this in either [`HashMap`] or [`BTreeMap`] and call it a day.\\nAnd that would be boring\u2026\\n\\n:::tip\\n\\n`BTreeMap` is quite fitting for this, don\'t you think?\\n\\n:::\\n\\nI always wanted to try allocation on heap in Rust, so I chose to implement a tree.\\nI fought with the `Box<T>` for some time and was losing\u2026\\n\\nThen I looked up some implementations of trees or linked lists and decided to try\\n`Rc<Cell<T>>`. And I got my _ass whopped_ by the compiler once again. /o\\\\\\n\\n:::tip\\n\\n`Box<T>` represents a dynamically allocated memory on heap. It is a single pointer,\\nyou can imagine this as `std::unique_ptr<T>` in C++.\\n\\n`Rc<T>` represents a dynamically allocated memory on heap. On top of that it is\\n_reference counted_ (that\'s what the `Rc` stands for). You can imagine this as\\n`std::shared_ptr<T>` in C++.\\n\\nNow the fun stuff. Neither of them lets you **mutate** the contents of the memory.\\n\\n`Cell<T>` allows you to mutate the memory. Can be used reasonably with types that\\ncan be copied, because the memory safety is guaranteed by copying the contents\\nwhen there is more than one **mutable** reference to the memory.\\n\\n`RefCell<T>` is similar to the `Cell<T>`, but the borrowing rules (how many mutable\\nreferences are present) are checked dynamically.\\n\\nSo in the end, if you want something like `std::shared_ptr<T>` in Rust, you want\\nto have `Rc<RefCell<T>>`.\\n\\n:::\\n\\nSo, how are we going to represent the file system then? We will use an enumeration,\\nhehe, which is an algebraic data type that can store some stuff in itself :weary:\\n```rust\\ntype FileHandle = Rc<RefCell<AocFile>>;\\n\\n#[derive(Debug)]\\nenum AocFile {\\n File(usize),\\n Directory(BTreeMap<String, FileHandle>),\\n}\\n```\\n\\nLet\'s go over it! `FileHandle` represents dynamically allocated `AocFile`, not\\nmuch to discuss. What does the `#[derive(Debug)]` do though? It lets us to print\\nout the value of that enumeration, it\'s derived, so it\'s not as good as if we had\\nimplemented it ourselves, but it\'s good enough for debugging, hence the name.\\n\\nNow to the fun part! `AocFile` value can be represented in two ways:\\n- `File(usize)`, e.g. `AocFile::File(123)` and we can pattern match it, if we\\n need to\\n- `Directory(BTreeMap<String, FileHandle>)` will represent the directory and will\\n contain map matching the name of the files (or directories) within to their\\n respective file handles\\n\\nI will omit the details about constructing this file system, cause there are a lot\\nof technicalities introduced by the nature of the input. However if you are\\ninterested, you can have a look at my solution.\\n\\nWe need to find small enough directories and also find the smallest directory that\\nwill free enough space. Now the question is, how could we do that. And there are\\nmultiple ways I will describe.\\n\\nI have chosen to implement [_tree catamorphism_] :weary:. It is basically a fold\\nover a tree data structure. We descent down into the leaves and propagate computed\\nresults all the way to the root. You can also notice that this approach is very\\nsimilar to _dynamic programming_, we find overlapping sections of the computation\\nand try to minimize the additional work (in this case: we need to know sizes of\\nour descendants, but we have already been there).\\n\\nAnother approach that has been suggested to me few days later is running DFS on\\nthe graph. And, funnily enough, we would still need to combine what we found in\\nthe branches where we descent. So in the end, it would work very similarly to my\\nsolution.\\n\\nOne of the more exotic options would be precomputing the required information at\\nthe same time as parsing. That could be done by adding additional fields to the\\nnodes which would allow storing such information and updating it as we construct\\nthe file system.\\n\\n## Post Mortem\\n\\nThings that have been brought up in the discussion later on.\\n\\n### `Rc<T>` vs `Rc<RefCell<T>>`\\n\\nIt has been brought up that I have a contradicting statement regarding the\\ndynamically allocated memory. Specifically:\\n\\n- You can imagine `Rc<T>` as an `std::shared_ptr<T>` (in C++)\\n- When you want an equivalent of `std::shared_ptr<T>`, you want to use\\n `Rc<RefCell<T>>`\\n\\nNow, in Rust it is a bit more complicated, because the type that represents the\\n\u201cshared pointer\u201d is `Rc<T>`. What `RefCell<T>` does is making sure that there is\\nonly one \u201cowner\u201d of a mutable reference at a time (and dynamically, as opposed\\nto the `Cell<T>`).\\n\\nTherefore to be precise and correct about the equivalents of `std::shared_ptr<T>`\\nin Rust, we can say that\\n\\n- `Rc<T>` is an equivalent of a `const std::shared_ptr<T>`,\\n- and `Rc<RefCell<T>>` is an equivalent of a `std::shared_ptr<T>`.\\n\\nYou can easily see that they only differ in the mutability. (And even that is not\\nas simple as it seems, because there is also `Cell<T>`)\\n\\n[_Advent of Code_]: https://adventofcode.com\\n[GitLab]: https://gitlab.com/mfocko/advent-of-code-2022\\n[`/src/bin/`]: https://gitlab.com/mfocko/advent-of-code-2022/-/tree/main/src/bin\\n[`sccache`]: https://github.com/mozilla/sccache\\n[`RangeInclusive`]: https://doc.rust-lang.org/std/ops/struct.RangeInclusive.html\\n[`split_off`]: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.split_off\\n[`du`]: https://www.man7.org/linux/man-pages/man1/du.1.html\\n[`HashMap`]: https://doc.rust-lang.org/std/collections/struct.HashMap.html\\n[`BTreeMap`]: https://doc.rust-lang.org/std/collections/struct.BTreeMap.html\\n[_tree catamorphism_]: https://en.wikipedia.org/wiki/Catamorphism#Tree_fold"},{"id":"aoc-2022/intro","metadata":{"permalink":"/blog/aoc-2022/intro","editUrl":"https://github.com/mfocko/blog/tree/main/blog/aoc-2022/00-intro.md","source":"@site/blog/aoc-2022/00-intro.md","title":"Advent of Code \'22 in Rust","description":"Preparing for Advent of Code \'22.","date":"2022-12-14T21:45:00.000Z","formattedDate":"December 14, 2022","tags":[{"label":"advent-of-code","permalink":"/blog/tags/advent-of-code"},{"label":"advent-of-code-2022","permalink":"/blog/tags/advent-of-code-2022"},{"label":"rust","permalink":"/blog/tags/rust"}],"readingTime":8.665,"hasTruncateMarker":true,"authors":[{"name":"Matej Focko","email":"me+blog@mfocko.xyz","title":"a.k.a. @mf","url":"https://gitlab.com/mfocko","imageURL":"https://github.com/mfocko.png","key":"mf"}],"frontMatter":{"title":"Advent of Code \'22 in Rust","description":"Preparing for Advent of Code \'22.","date":"2022-12-14T21:45","slug":"aoc-2022/intro","authors":"mf","tags":["advent-of-code","advent-of-code-2022","rust"],"hide_table_of_contents":false},"unlisted":false,"prevItem":{"title":"1st week of Advent of Code \'22 in Rust","permalink":"/blog/aoc-2022/1st-week"}},"content":"Let\'s talk about the preparations for this year\'s [_Advent of Code_].\\n\\n\x3c!--truncate--\x3e\\n\\n## Choosing a language\\n\\nWhen choosing a language for AoC, you usually want a language that gives you a\\nquick feedback which allows you to iterate quickly to the solution of the puzzle.\\nOne of the most common choices is Python, many people also use JavaScript or Ruby.\\n\\nGiven the competitive nature of the AoC and popularity among competitive programming,\\nC++ might be also a very good choice. Only if you are familiar with it, I guess\u2026\\n\\nIf you want a challenge, you might also choose to rotate the languages each day.\\nThough I prefer to use only one language.\\n\\nFor this year I have been deciding between _Rust_, _C++_ and _Pascal_ or _Ada_.\\n\\nI have tried Rust last year and have survived with it for 3 days and then gave\\nup and switched to _Kotlin_, which was pretty good given it is \u201cJava undercover\u201d.\\nI pretty much like the ideas behind Rust, I am not sure about the whole cult and\\nimplementation of those ideas though. After some years with C/C++, I would say\\nthat Rust feels _too safe_ for my taste and tries to \u201c_punish me_\u201d even for the\\nmost trivial things.\\n\\nC++ is a very robust, but also comes with a wide variety of options providing you\\nthe ability to shoot yourself in the leg. I have tried to solve few days of previous\\nAdvent of Code events, it was _relatively easy_ to solve the problems in C++, given\\nthat I do not admit writing my own iterator for `enumerate`\u2026\\n\\nPascal or Ada were meme choices :) Ada is heavily inspired by Pascal and has a\\npretty nice standard library that offers enough to be able to quickly solve some\\nproblems in it. However the toolkit is questionable :/\\n\\n## Choosing libraries\\n\\n## Preparations for Rust\\n\\nAll of the sources, later on including solutions, can be found at my\\n[GitLab].\\n\\n### Toolkit\\n\\nSince we are using Rust, we are going to use a [Cargo] and more than likely VSCode\\nwith [`rust-analyzer`]. Because of my choice of libraries, we will also introduce\\na `.envrc` file that can be used by [`direnv`], which allows you to set specific\\nenvironment variables when you enter a directory. In our case, we will use\\n```bash\\n# to show nice backtrace when using the color-eyre\\nexport RUST_BACKTRACE=1\\n\\n# to catch logs generated by tracing\\nexport RUST_LOG=trace\\n```\\n\\nAnd for the one of the most obnoxious things ever, we will use a script to download\\nthe inputs instead of \u201c_clicking, opening and copying to a file_\u201d[^1]. There is\\nno need to be _fancy_, so we will adjust Python script by Martin[^2].\\n```py\\n#!/usr/bin/env python3\\n\\nimport datetime\\nimport yaml\\nimport requests\\nimport sys\\n\\n\\ndef load_config():\\n with open(\\"env.yaml\\", \\"r\\") as f:\\n js = yaml.load(f, Loader=yaml.Loader)\\n return js[\\"session\\"], js[\\"year\\"]\\n\\n\\ndef get_input(session, year, day):\\n return requests.get(\\n f\\"https://adventofcode.com/{year}/day/{day}/input\\",\\n cookies={\\"session\\": session},\\n headers={\\n \\"User-Agent\\": \\"{repo} by {mail}\\".format(\\n repo=\\"gitlab.com/mfocko/advent-of-code-2022\\",\\n mail=\\"me@mfocko.xyz\\",\\n )\\n },\\n ).content.decode(\\"utf-8\\")\\n\\n\\ndef main():\\n day = datetime.datetime.now().day\\n if len(sys.argv) == 2:\\n day = sys.argv[1]\\n\\n session, year = load_config()\\n problem_input = get_input(session, year, day)\\n\\n with open(f\\"./inputs/day{day:>02}.txt\\", \\"w\\") as f:\\n f.write(problem_input)\\n\\n\\nif __name__ == \\"__main__\\":\\n main()\\n```\\n\\nIf the script is called without any arguments, it will deduce the day from the\\nsystem, so we do not need to change the day every morning. It also requires a\\nconfiguration file:\\n```yaml\\n# env.yaml\\nsession: \u2039your session cookie\u203a\\nyear: 2022\\n```\\n\\n### Libraries\\n\\nLooking at the list of the libraries, I have chosen \u201ca lot\u201d of them. Let\'s walk\\nthrough each of them.\\n\\n[`tracing`] and [`tracing-subscriber`] are the crates that can be used for tracing\\nand logging of your Rust programs, there are also other crates that can help you\\nwith providing backtrace to the Sentry in case you have deployed your application\\nsomewhere and you want to watch over it. In our use case we will just utilize the\\nmacros for debugging in the terminal.\\n\\n[`thiserror`], [`anyhow`] and [`color-eyre`] are used for error reporting.\\n`thiserror` is a very good choice for libraries, cause it extends the `Error`\\nfrom the `std` and allows you to create more convenient error types. Next is\\n`anyhow` which kinda builds on top of the `thiserror` and provides you with simpler\\nerror handling in binaries[^3]. And finally we have `color-eyre` which, as I found\\nout later, is a colorful (_wink wink_) extension of `eyre` which is fork of `anyhow`\\nwhile supporting customized reports.\\n\\nIn the end I have decided to remove `thiserror` and `anyhow`, since first one is\\nsuitable for libraries and the latter was basically fully replaced by `{color-,}eyre`.\\n\\n[`regex`] and [`lazy_static`] are a very good and also, I hope, self-explanatory\\ncombination. `lazy_static` allows you to have static variables that must be initialized\\nduring runtime.\\n\\n[`itertools`] provides some nice extensions to the iterators from the `std`.\\n\\n### My own \u201clibrary\u201d\\n\\nWhen creating the crate for this year\'s Advent of Code, I have chosen a library\\ntype. Even though standard library is huge, some things might not be included and\\nalso we can follow _KISS_. I have 2 modules that my \u201clibrary\u201d exports, one for\\nparsing and one for 2D vector (that gets used quite often during Advent of Code).\\n\\nKey part is, of course, processing the input and my library exports following\\nfunctions that get used a lot:\\n```rust\\n/// Reads file to the string.\\npub fn file_to_string<P: AsRef<Path>>(pathname: P) -> String;\\n\\n/// Reads file and returns it as a vector of characters.\\npub fn file_to_chars<P: AsRef<Path>>(pathname: P) -> Vec<char>;\\n\\n/// Reads file and returns a vector of parsed structures. Expects each structure\\n/// on its own line in the file. And `T` needs to implement `FromStr` trait.\\npub fn file_to_structs<P: AsRef<Path>, T: FromStr>(pathname: P) -> Vec<T>\\nwhere\\n <T as FromStr>::Err: Debug;\\n\\n/// Converts iterator over strings to a vector of parsed structures. `T` needs\\n/// to implement `FromStr` trait and its error must derive `Debug` trait.\\npub fn strings_to_structs<T: FromStr, U>(\\n iter: impl Iterator<Item = U>\\n) -> Vec<T>\\nwhere\\n <T as std::str::FromStr>::Err: std::fmt::Debug,\\n U: Deref<Target = str>;\\n\\n/// Reads file and returns it as a vector of its lines.\\npub fn file_to_lines<P: AsRef<Path>>(pathname: P) -> Vec<String>;\\n```\\n\\nAs for the vector, I went with a rather simple implementation that allows only\\naddition of the vectors for now and accessing the elements via functions `x()`\\nand `y()`. Also the vector is generic, so we can use it with any numeric type we\\nneed.\\n\\n### Skeleton\\n\\nWe can also prepare a template to quickly bootstrap each of the days. We know\\nthat each puzzle has 2 parts, which means that we can start with 2 functions that\\nwill solve them.\\n```rust\\nfn part1(input: &Input) -> Output {\\n todo!()\\n}\\n\\nfn part2(input: &Input) -> Output {\\n todo!()\\n}\\n```\\n\\nBoth functions take reference to the input and return some output (in majority\\nof puzzles, it is the same type). `todo!()` can be used as a nice placeholder,\\nit also causes a panic when reached and we could also provide some string with\\nan explanation, e.g. `todo!(\\"part 1\\")`. We have not given functions a specific\\ntype and to avoid as much copy-paste as possible, we will introduce type aliases.\\n```rust\\ntype Input = String;\\ntype Output = i32;\\n```\\n\\n:::tip\\n\\nThis allows us to quickly adjust the types only in one place without the need to\\ndo _regex-replace_ or replace them manually.\\n\\n:::\\n\\nFor each day we get a personalized input that is provided as a text file. Almost\\nall the time, we would like to get some structured type out of that input, and\\ntherefore it makes sense to introduce a new function that will provide the parsing\\nof the input.\\n```rust\\nfn parse_input(path: &str) -> Input {\\n todo!()\\n}\\n```\\n\\nThis \u201cparser\u201d will take a path to the file, just in case we would like to run the\\nsample instead of input.\\n\\nOK, so now we can write a `main` function that will take all of the pieces and\\nrun them.\\n```rust\\nfn main() {\\n let input = parse_input(\\"inputs/dayXX.txt\\");\\n\\n println!(\\"Part 1: {}\\", part_1(&input));\\n println!(\\"Part 2: {}\\", part_2(&input));\\n}\\n```\\n\\nThis would definitely do :) But we have installed a few libraries and we want to\\nuse them. In this part we are going to utilize _[`tracing`]_ (for tracing, duh\u2026)\\nand _[`color-eyre`]_ (for better error reporting, e.g. from parsing).\\n```rust\\nfn main() -> Result<()> {\\n tracing_subscriber::fmt()\\n .with_env_filter(EnvFilter::from_default_env())\\n .with_target(false)\\n .with_file(true)\\n .with_line_number(true)\\n .without_time()\\n .compact()\\n .init();\\n color_eyre::install()?;\\n\\n let input = parse_input(\\"inputs/dayXX.txt\\");\\n\\n info!(\\"Part 1: {}\\", part_1(&input));\\n info!(\\"Part 2: {}\\", part_2(&input));\\n\\n Ok(())\\n}\\n```\\n\\nThe first statement will set up tracing and configure it to print out the logs to\\nterminal, based on the environment variable. We also change the formatting a bit,\\nsince we do not need all the _fancy_ features of the logger. Pure initialization\\nwould get us logs like this:\\n```\\n2022-12-11T19:53:19.975343Z INFO day01: Part 1: 0\\n```\\n\\nHowever after running that command, we will get the following:\\n```\\n INFO src/bin/day01.rs:35: Part 1: 0\\n```\\n\\nAnd the `color_eyre::install()?` is quite straightforward. We just initialize the\\nerror reporting by _color eyre_.\\n\\n:::caution\\n\\nNotice that we had to add `Ok(())` to the end of the function and adjust the\\nreturn type of the `main` to `Result<()>`. It is caused by the _color eyre_ that\\ncan be installed only once and therefore it can fail, that is how we got the `?`\\nat the end of the `::install` which _unwraps_ the **\xbbresult\xab** of the installation.\\n\\n:::\\n\\nOverall we will get to a template like this:\\n```rust\\nuse aoc_2022::*;\\n\\nuse color_eyre::eyre::Result;\\nuse tracing::info;\\nuse tracing_subscriber::EnvFilter;\\n\\ntype Input = String;\\ntype Output = i32;\\n\\nfn parse_input(path: &str) -> Input {\\n todo!()\\n}\\n\\nfn part1(input: &Input) -> Output {\\n todo!()\\n}\\n\\nfn part2(input: &Input) -> Output {\\n todo!()\\n}\\n\\nfn main() -> Result<()> {\\n tracing_subscriber::fmt()\\n .with_env_filter(EnvFilter::from_default_env())\\n .with_target(false)\\n .with_file(true)\\n .with_line_number(true)\\n .without_time()\\n .compact()\\n .init();\\n color_eyre::install()?;\\n\\n let input = parse_input(\\"inputs/dayXX.txt\\");\\n\\n info!(\\"Part 1: {}\\", part_1(&input));\\n info!(\\"Part 2: {}\\", part_2(&input));\\n\\n Ok(())\\n}\\n```\\n\\n[^1]: Copy-pasting might be a relaxing thing to do, but you can also discover\\nnasty stuff about your PC. See [this Reddit post and the comment].\\n[^2]: [GitHub profile](https://github.com/martinjonas)\\n[^3]: Even though you can use it even for libraries, but handling errors from\\nlibraries using `anyhow` is nasty\u2026 You will be the stinky one ;)\\n\\n[_Advent of Code_]: https://adventofcode.com\\n[GitLab]: https://gitlab.com/mfocko/advent-of-code-2022\\n[Cargo]: https://doc.rust-lang.org/cargo/\\n[`rust-analyzer`]: https://rust-analyzer.github.io/\\n[`direnv`]: https://direnv.net/\\n[`tracing`]: https://crates.io/crates/tracing\\n[`tracing-subscriber`]: https://crates.io/crates/tracing-subscriber\\n[`thiserror`]: https://crates.io/crates/thiserror\\n[`anyhow`]: https://crates.io/crates/anyhow\\n[`color-eyre`]: https://crates.io/crates/color-eyre\\n[`regex`]: https://crates.io/crates/regex\\n[`lazy_static`]: https://crates.io/crates/lazy_static\\n[`itertools`]: https://crates.io/crates/itertools\\n[this Reddit post and the comment]: https://www.reddit.com/r/adventofcode/comments/zb98pn/comment/iyq0ono"}]}')}}]);