diff --git a/404.html b/404.html index 7094698..1636bf9 100644 --- a/404.html +++ b/404.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/algorithms-correctness/postcondition-ambiguity/index.html b/algorithms/algorithms-correctness/postcondition-ambiguity/index.html index f68c46e..0e018e2 100644 --- a/algorithms/algorithms-correctness/postcondition-ambiguity/index.html +++ b/algorithms/algorithms-correctness/postcondition-ambiguity/index.html @@ -16,7 +16,7 @@ - + diff --git a/algorithms/category/algorithms-and-correctness/index.html b/algorithms/category/algorithms-and-correctness/index.html index 773cfcc..44d17de 100644 --- a/algorithms/category/algorithms-and-correctness/index.html +++ b/algorithms/category/algorithms-and-correctness/index.html @@ -18,7 +18,7 @@ correctness. - + diff --git a/algorithms/category/asymptotic-notation-and-time-complexity/index.html b/algorithms/category/asymptotic-notation-and-time-complexity/index.html index d6d0535..60a3dfc 100644 --- a/algorithms/category/asymptotic-notation-and-time-complexity/index.html +++ b/algorithms/category/asymptotic-notation-and-time-complexity/index.html @@ -16,7 +16,7 @@ - + diff --git a/algorithms/category/graphs/index.html b/algorithms/category/graphs/index.html index 104f057..52730db 100644 --- a/algorithms/category/graphs/index.html +++ b/algorithms/category/graphs/index.html @@ -16,7 +16,7 @@ - + diff --git a/algorithms/category/hash-tables/index.html b/algorithms/category/hash-tables/index.html index 45ebdbf..41edc2e 100644 --- a/algorithms/category/hash-tables/index.html +++ b/algorithms/category/hash-tables/index.html @@ -16,7 +16,7 @@ - + diff --git a/algorithms/category/paths-in-graphs/index.html b/algorithms/category/paths-in-graphs/index.html index 69636ae..13b5c76 100644 --- a/algorithms/category/paths-in-graphs/index.html +++ b/algorithms/category/paths-in-graphs/index.html @@ -16,7 +16,7 @@ - + diff --git a/algorithms/category/recursion/index.html b/algorithms/category/recursion/index.html index 2e77fe6..90c971e 100644 --- a/algorithms/category/recursion/index.html +++ b/algorithms/category/recursion/index.html @@ -16,7 +16,7 @@ - + diff --git a/algorithms/category/red-black-trees/index.html b/algorithms/category/red-black-trees/index.html index ccd4a1a..23bb967 100644 --- a/algorithms/category/red-black-trees/index.html +++ b/algorithms/category/red-black-trees/index.html @@ -16,7 +16,7 @@ - + diff --git a/algorithms/graphs/bfs-tree/index.html b/algorithms/graphs/bfs-tree/index.html index 252fbac..26d24b5 100644 --- a/algorithms/graphs/bfs-tree/index.html +++ b/algorithms/graphs/bfs-tree/index.html @@ -16,7 +16,7 @@ - + diff --git a/algorithms/graphs/iterative-and-iterators/index.html b/algorithms/graphs/iterative-and-iterators/index.html index bdc66ba..72435cc 100644 --- a/algorithms/graphs/iterative-and-iterators/index.html +++ b/algorithms/graphs/iterative-and-iterators/index.html @@ -16,7 +16,7 @@ - + diff --git a/algorithms/hash-tables/breaking/index.html b/algorithms/hash-tables/breaking/index.html index 976322c..8af3162 100644 --- a/algorithms/hash-tables/breaking/index.html +++ b/algorithms/hash-tables/breaking/index.html @@ -16,7 +16,7 @@ - + diff --git a/algorithms/hash-tables/breaking/mitigations/index.html b/algorithms/hash-tables/breaking/mitigations/index.html index aea5a93..442d44a 100644 --- a/algorithms/hash-tables/breaking/mitigations/index.html +++ b/algorithms/hash-tables/breaking/mitigations/index.html @@ -16,7 +16,7 @@ - + diff --git a/algorithms/hash-tables/breaking/python/index.html b/algorithms/hash-tables/breaking/python/index.html index bd5d99e..00c0ed2 100644 --- a/algorithms/hash-tables/breaking/python/index.html +++ b/algorithms/hash-tables/breaking/python/index.html @@ -16,7 +16,7 @@ - + diff --git a/algorithms/index.html b/algorithms/index.html index a250af1..7b7fcd1 100644 --- a/algorithms/index.html +++ b/algorithms/index.html @@ -14,7 +14,7 @@ - + @@ -23,6 +23,6 @@ course of teaching Algorithms and data structures I.

It is a various mix of stuff that may have been produced as a follow-up on some question asked at the seminar or spontanously.

If you have some ideas for posts, please do not hesitate to submit them as issues -in the linked GitLab.

+in the linked GitLab.

\ No newline at end of file diff --git a/algorithms/paths/bf-to-astar/astar/index.html b/algorithms/paths/bf-to-astar/astar/index.html index fa4d367..0522a1a 100644 --- a/algorithms/paths/bf-to-astar/astar/index.html +++ b/algorithms/paths/bf-to-astar/astar/index.html @@ -16,7 +16,7 @@ - + diff --git a/algorithms/paths/bf-to-astar/bf/index.html b/algorithms/paths/bf-to-astar/bf/index.html index bb90723..514667a 100644 --- a/algorithms/paths/bf-to-astar/bf/index.html +++ b/algorithms/paths/bf-to-astar/bf/index.html @@ -18,7 +18,7 @@ something. - + diff --git a/algorithms/paths/bf-to-astar/dijkstra/index.html b/algorithms/paths/bf-to-astar/dijkstra/index.html index c15a994..55cbd4f 100644 --- a/algorithms/paths/bf-to-astar/dijkstra/index.html +++ b/algorithms/paths/bf-to-astar/dijkstra/index.html @@ -16,7 +16,7 @@ - + diff --git a/algorithms/paths/bf-to-astar/index.html b/algorithms/paths/bf-to-astar/index.html index e748a91..299ef8c 100644 --- a/algorithms/paths/bf-to-astar/index.html +++ b/algorithms/paths/bf-to-astar/index.html @@ -16,7 +16,7 @@ - + @@ -56,7 +56,7 @@ two positions on the map made

We can see the graph header here:

-
#ifndef _GRAPH_HPP
#define _GRAPH_HPP

#include <cmath>
#include <limits>
#include <ostream>
#include <utility>
#include <vector>

using vertex_t = std::pair<int, int>;

struct graph {
graph(const std::vector<std::vector<char>>& map)
: map(map),
_height(static_cast<int>(map.size())),
_width(map.empty() ? 0 : static_cast<int>(map[0].size())) {}

static auto unreachable() -> int { return UNREACHABLE; }
static auto normal_cost() -> int { return NORMAL_COST; }
static auto vortex_cost() -> int { return VORTEX_COST; }

auto cost(const vertex_t& u, const vertex_t& v) const -> int {
auto [ux, uy] = u;
auto [vx, vy] = v;

auto hd = std::abs(ux - vx) + std::abs(uy - vy);
switch (hd) {
// ‹u = v›; staying on the same cell
case 0:
return 0;
// ‹u› and ‹v› are neighbours
case 1:
break;
// ‹u› and ‹v› are not neighbouring cells
default:
return UNREACHABLE;
}

// boundary check
if (vy < 0 || vy >= _height || vx < 0 || vx >= _width) {
return UNREACHABLE;
}

switch (map[vy][vx]) {
case '#':
return UNREACHABLE;
case '*':
return VORTEX_COST;
default:
return NORMAL_COST;
}
}

auto width() const -> int { return _width; }
auto height() const -> int { return _height; }
auto has(const vertex_t& v) const -> bool {
auto [x, y] = v;
return (0 <= y && y < _height) && (0 <= x && x < _width);
}

friend std::ostream& operator<<(std::ostream& os, const graph& g);

private:
std::vector<std::vector<char>> map;
int _height, _width;

const static int UNREACHABLE = std::numeric_limits<int>::max();
// XXX: modify here to change the price of entering the vortex
const static int VORTEX_COST = 5;
const static int NORMAL_COST = 1;
};

std::ostream& operator<<(std::ostream& os, const graph& g) {
for (const auto& row : g.map) {
for (const char cell : row) {
os << cell;
}
os << "\n";
}

return os;
}

#endif /* _GRAPH_HPP */
+
#ifndef _GRAPH_HPP
#define _GRAPH_HPP

#include <cmath>
#include <limits>
#include <ostream>
#include <utility>
#include <vector>

using vertex_t = std::pair<int, int>;

struct graph {
graph(const std::vector<std::vector<char>>& map)
: map(map),
_height(static_cast<int>(map.size())),
_width(map.empty() ? 0 : static_cast<int>(map[0].size())) {}

static auto unreachable() -> int { return UNREACHABLE; }
static auto normal_cost() -> int { return NORMAL_COST; }
static auto vortex_cost() -> int { return VORTEX_COST; }

auto cost(const vertex_t& u, const vertex_t& v) const -> int {
auto [ux, uy] = u;
auto [vx, vy] = v;

auto md = std::abs(ux - vx) + std::abs(uy - vy);
switch (md) {
// ‹u = v›; staying on the same cell
case 0:
return 0;
// ‹u› and ‹v› are neighbours
case 1:
break;
// ‹u› and ‹v› are not neighbouring cells
default:
return UNREACHABLE;
}

// boundary check
if (vy < 0 || vy >= _height || vx < 0 || vx >= _width) {
return UNREACHABLE;
}

switch (map[vy][vx]) {
case '#':
return UNREACHABLE;
case '*':
return VORTEX_COST;
default:
return NORMAL_COST;
}
}

auto width() const -> int { return _width; }
auto height() const -> int { return _height; }
auto has(const vertex_t& v) const -> bool {
auto [x, y] = v;
return (0 <= y && y < _height) && (0 <= x && x < _width);
}

friend std::ostream& operator<<(std::ostream& os, const graph& g);

private:
std::vector<std::vector<char>> map;
int _height, _width;

const static int UNREACHABLE = std::numeric_limits<int>::max();
// XXX: modify here to change the price of entering the vortex
const static int VORTEX_COST = 5;
const static int NORMAL_COST = 1;
};

std::ostream& operator<<(std::ostream& os, const graph& g) {
for (const auto& row : g.map) {
for (const char cell : row) {
os << cell;
}
os << "\n";
}

return os;
}

#endif /* _GRAPH_HPP */
Source code

You can find all the source code referenced in this series here.

Let's finally start with some algorithms!

diff --git a/algorithms/rb-trees/applications/index.html b/algorithms/rb-trees/applications/index.html index 3e642c5..55c60a6 100644 --- a/algorithms/rb-trees/applications/index.html +++ b/algorithms/rb-trees/applications/index.html @@ -16,7 +16,7 @@ - + diff --git a/algorithms/rb-trees/rules/index.html b/algorithms/rb-trees/rules/index.html index 3e3323f..45482cf 100644 --- a/algorithms/rb-trees/rules/index.html +++ b/algorithms/rb-trees/rules/index.html @@ -16,7 +16,7 @@ - + diff --git a/algorithms/recursion/karel/index.html b/algorithms/recursion/karel/index.html index 6843fe2..e58387b 100644 --- a/algorithms/recursion/karel/index.html +++ b/algorithms/recursion/karel/index.html @@ -16,7 +16,7 @@ - + diff --git a/algorithms/recursion/karel/solution/index.html b/algorithms/recursion/karel/solution/index.html index 62fe2ff..e9fbf09 100644 --- a/algorithms/recursion/karel/solution/index.html +++ b/algorithms/recursion/karel/solution/index.html @@ -16,7 +16,7 @@ - + diff --git a/algorithms/recursion/pyramid-slide-down/bottom-up-dp/index.html b/algorithms/recursion/pyramid-slide-down/bottom-up-dp/index.html index b9ab384..6320266 100644 --- a/algorithms/recursion/pyramid-slide-down/bottom-up-dp/index.html +++ b/algorithms/recursion/pyramid-slide-down/bottom-up-dp/index.html @@ -16,7 +16,7 @@ - + diff --git a/algorithms/recursion/pyramid-slide-down/greedy/index.html b/algorithms/recursion/pyramid-slide-down/greedy/index.html index c6a1612..a0befdb 100644 --- a/algorithms/recursion/pyramid-slide-down/greedy/index.html +++ b/algorithms/recursion/pyramid-slide-down/greedy/index.html @@ -16,7 +16,7 @@ - + diff --git a/algorithms/recursion/pyramid-slide-down/index.html b/algorithms/recursion/pyramid-slide-down/index.html index 05a0b58..c24925b 100644 --- a/algorithms/recursion/pyramid-slide-down/index.html +++ b/algorithms/recursion/pyramid-slide-down/index.html @@ -16,7 +16,7 @@ - + diff --git a/algorithms/recursion/pyramid-slide-down/naive/index.html b/algorithms/recursion/pyramid-slide-down/naive/index.html index 835fcce..9daeda7 100644 --- a/algorithms/recursion/pyramid-slide-down/naive/index.html +++ b/algorithms/recursion/pyramid-slide-down/naive/index.html @@ -16,7 +16,7 @@ - + diff --git a/algorithms/recursion/pyramid-slide-down/top-down-dp/index.html b/algorithms/recursion/pyramid-slide-down/top-down-dp/index.html index 787c161..9e6698d 100644 --- a/algorithms/recursion/pyramid-slide-down/top-down-dp/index.html +++ b/algorithms/recursion/pyramid-slide-down/top-down-dp/index.html @@ -16,7 +16,7 @@ - + diff --git a/algorithms/tags/a-star/index.html b/algorithms/tags/a-star/index.html index 431fa40..3637405 100644 --- a/algorithms/tags/a-star/index.html +++ b/algorithms/tags/a-star/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/applications/index.html b/algorithms/tags/applications/index.html index e29794e..cd58f2a 100644 --- a/algorithms/tags/applications/index.html +++ b/algorithms/tags/applications/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/astar/index.html b/algorithms/tags/astar/index.html index b7983e7..eb9a142 100644 --- a/algorithms/tags/astar/index.html +++ b/algorithms/tags/astar/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/backtracking/index.html b/algorithms/tags/backtracking/index.html index 8d61ace..dcf4599 100644 --- a/algorithms/tags/backtracking/index.html +++ b/algorithms/tags/backtracking/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/balanced-trees/index.html b/algorithms/tags/balanced-trees/index.html index 01a8d3f..608e4f8 100644 --- a/algorithms/tags/balanced-trees/index.html +++ b/algorithms/tags/balanced-trees/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/bellman-ford/index.html b/algorithms/tags/bellman-ford/index.html index 7e12f68..9cfec35 100644 --- a/algorithms/tags/bellman-ford/index.html +++ b/algorithms/tags/bellman-ford/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/bfs/index.html b/algorithms/tags/bfs/index.html index 2421be4..2478b5c 100644 --- a/algorithms/tags/bfs/index.html +++ b/algorithms/tags/bfs/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/bottom-up-dp/index.html b/algorithms/tags/bottom-up-dp/index.html index c7e9e7a..1168caa 100644 --- a/algorithms/tags/bottom-up-dp/index.html +++ b/algorithms/tags/bottom-up-dp/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/brute-force/index.html b/algorithms/tags/brute-force/index.html index ee453c9..c8ae685 100644 --- a/algorithms/tags/brute-force/index.html +++ b/algorithms/tags/brute-force/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/c/index.html b/algorithms/tags/c/index.html index 0a2aef2..90faa96 100644 --- a/algorithms/tags/c/index.html +++ b/algorithms/tags/c/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/cpp/index.html b/algorithms/tags/cpp/index.html index 805e190..c186b1d 100644 --- a/algorithms/tags/cpp/index.html +++ b/algorithms/tags/cpp/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/csharp/index.html b/algorithms/tags/csharp/index.html index b180c87..2be24e8 100644 --- a/algorithms/tags/csharp/index.html +++ b/algorithms/tags/csharp/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/dijkstra/index.html b/algorithms/tags/dijkstra/index.html index 0def4d2..5aa7618 100644 --- a/algorithms/tags/dijkstra/index.html +++ b/algorithms/tags/dijkstra/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/dynamic-array/index.html b/algorithms/tags/dynamic-array/index.html index a616811..4749cd5 100644 --- a/algorithms/tags/dynamic-array/index.html +++ b/algorithms/tags/dynamic-array/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/dynamic-programming/index.html b/algorithms/tags/dynamic-programming/index.html index 446f06b..9ae1a5e 100644 --- a/algorithms/tags/dynamic-programming/index.html +++ b/algorithms/tags/dynamic-programming/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/exponential/index.html b/algorithms/tags/exponential/index.html index e93b067..af52743 100644 --- a/algorithms/tags/exponential/index.html +++ b/algorithms/tags/exponential/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/graphs/index.html b/algorithms/tags/graphs/index.html index 482900a..ba2efc3 100644 --- a/algorithms/tags/graphs/index.html +++ b/algorithms/tags/graphs/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/greedy/index.html b/algorithms/tags/greedy/index.html index 1a5424f..8f6126b 100644 --- a/algorithms/tags/greedy/index.html +++ b/algorithms/tags/greedy/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/hash-tables/index.html b/algorithms/tags/hash-tables/index.html index 99f15c9..06a3508 100644 --- a/algorithms/tags/hash-tables/index.html +++ b/algorithms/tags/hash-tables/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/index.html b/algorithms/tags/index.html index ad8f329..5526f2d 100644 --- a/algorithms/tags/index.html +++ b/algorithms/tags/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/iterative/index.html b/algorithms/tags/iterative/index.html index 46cff49..ea1c4d0 100644 --- a/algorithms/tags/iterative/index.html +++ b/algorithms/tags/iterative/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/iterators/index.html b/algorithms/tags/iterators/index.html index 1432ba3..92efb44 100644 --- a/algorithms/tags/iterators/index.html +++ b/algorithms/tags/iterators/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/java/index.html b/algorithms/tags/java/index.html index 12c8f47..fb26970 100644 --- a/algorithms/tags/java/index.html +++ b/algorithms/tags/java/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/karel/index.html b/algorithms/tags/karel/index.html index 73e4fc0..276c9f1 100644 --- a/algorithms/tags/karel/index.html +++ b/algorithms/tags/karel/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/postconditions/index.html b/algorithms/tags/postconditions/index.html index 3a803ed..aa3d4e4 100644 --- a/algorithms/tags/postconditions/index.html +++ b/algorithms/tags/postconditions/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/python/index.html b/algorithms/tags/python/index.html index a25e9a1..3bd02e3 100644 --- a/algorithms/tags/python/index.html +++ b/algorithms/tags/python/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/recursion/index.html b/algorithms/tags/recursion/index.html index 9044d56..e9cba44 100644 --- a/algorithms/tags/recursion/index.html +++ b/algorithms/tags/recursion/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/red-black-trees/index.html b/algorithms/tags/red-black-trees/index.html index fa05a57..5d962f6 100644 --- a/algorithms/tags/red-black-trees/index.html +++ b/algorithms/tags/red-black-trees/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/solution/index.html b/algorithms/tags/solution/index.html index 8923f0a..6409b75 100644 --- a/algorithms/tags/solution/index.html +++ b/algorithms/tags/solution/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/sorting/index.html b/algorithms/tags/sorting/index.html index 4c8828d..9b414bc 100644 --- a/algorithms/tags/sorting/index.html +++ b/algorithms/tags/sorting/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/testing/index.html b/algorithms/tags/testing/index.html index 1fee8ab..42607ac 100644 --- a/algorithms/tags/testing/index.html +++ b/algorithms/tags/testing/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/time-complexity/index.html b/algorithms/tags/time-complexity/index.html index 1335d14..57c3cc1 100644 --- a/algorithms/tags/time-complexity/index.html +++ b/algorithms/tags/time-complexity/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/tags/top-down-dp/index.html b/algorithms/tags/top-down-dp/index.html index 3f1e22c..9bedb27 100644 --- a/algorithms/tags/top-down-dp/index.html +++ b/algorithms/tags/top-down-dp/index.html @@ -14,7 +14,7 @@ - + diff --git a/algorithms/time-complexity/extend/index.html b/algorithms/time-complexity/extend/index.html index 6ff6278..b01eda3 100644 --- a/algorithms/time-complexity/extend/index.html +++ b/algorithms/time-complexity/extend/index.html @@ -16,7 +16,7 @@ - + diff --git a/assets/js/1535ede8.102142f5.js b/assets/js/1535ede8.3c894b1e.js similarity index 99% rename from assets/js/1535ede8.102142f5.js rename to assets/js/1535ede8.3c894b1e.js index 94b5cab..d8aa4f0 100644 --- a/assets/js/1535ede8.102142f5.js +++ b/assets/js/1535ede8.3c894b1e.js @@ -1 +1 @@ -"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[5376],{44969:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>r,metadata:()=>a,toc:()=>l});var s=t(85893),i=t(11151);const r={id:"seminar-10",title:"10th seminar",description:"Finding bugs in a hangman.\n"},o=void 0,a={id:"bonuses/seminar-10",title:"10th seminar",description:"Finding bugs in a hangman.\n",source:"@site/c/bonuses/10.md",sourceDirName:"bonuses",slug:"/bonuses/seminar-10",permalink:"/c/bonuses/seminar-10",draft:!1,unlisted:!1,editUrl:"https://github.com/mfocko/blog/tree/main/c/bonuses/10.md",tags:[],version:"current",lastUpdatedAt:1704291155,formattedLastUpdatedAt:"Jan 3, 2024",frontMatter:{id:"seminar-10",title:"10th seminar",description:"Finding bugs in a hangman.\n"},sidebar:"autogeneratedBar",previous:{title:"8th seminar",permalink:"/c/bonuses/seminar-08"},next:{title:"Practice Exams",permalink:"/c/category/practice-exams"}},c={},l=[{value:"Introduction",id:"introduction",level:2},{value:"Project",id:"project",level:2},{value:"Summary of the gameplay",id:"summary-of-the-gameplay",level:3},{value:"Suggested workflow",id:"suggested-workflow",level:2},{value:"Tasks",id:"tasks",level:2},{value:"Dictionary",id:"dictionary",level:2},{value:"Submitting",id:"submitting",level:2}];function d(e){const n={a:"a",blockquote:"blockquote",code:"code",em:"em",h2:"h2",h3:"h3",hr:"hr",img:"img",li:"li",ol:"ol",p:"p",pre:"pre",table:"table",tbody:"tbody",td:"td",th:"th",thead:"thead",tr:"tr",ul:"ul",...(0,i.a)(),...e.components};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(n.p,{children:(0,s.jsx)(n.a,{href:"pathname:///files/c/bonuses/10.tar.gz",children:"Source"})}),"\n",(0,s.jsx)(n.h2,{id:"introduction",children:"Introduction"}),"\n",(0,s.jsx)(n.p,{children:"For this bonus you are given almost finished project - The Hangman Game. Your\ntask is to try the game, in case you find any bugs point them out and cover as\nmuch of the game as possible with tests."}),"\n",(0,s.jsx)(n.p,{children:"For this bonus you can get at maximum 2 K\u20a1."}),"\n",(0,s.jsxs)(n.table,{children:[(0,s.jsx)(n.thead,{children:(0,s.jsxs)(n.tr,{children:[(0,s.jsx)(n.th,{children:"Item"}),(0,s.jsx)(n.th,{children:"Bonus"})]})}),(0,s.jsxs)(n.tbody,{children:[(0,s.jsxs)(n.tr,{children:[(0,s.jsx)(n.td,{children:"Fixing bugs from failing tests"}),(0,s.jsx)(n.td,{children:"0.25"})]}),(0,s.jsxs)(n.tr,{children:[(0,s.jsx)(n.td,{children:(0,s.jsx)(n.code,{children:"word_guessed"})}),(0,s.jsx)(n.td,{children:"0.50"})]}),(0,s.jsxs)(n.tr,{children:[(0,s.jsx)(n.td,{children:"Hidden bug"}),(0,s.jsx)(n.td,{children:"0.50"})]}),(0,s.jsxs)(n.tr,{children:[(0,s.jsx)(n.td,{children:"Extending tests, undetectable bugs or evil bug"}),(0,s.jsx)(n.td,{children:"0.37"})]}),(0,s.jsxs)(n.tr,{children:[(0,s.jsx)(n.td,{children:"Refactor"}),(0,s.jsx)(n.td,{children:"0.38"})]})]})]}),"\n",(0,s.jsx)(n.h2,{id:"project",children:"Project"}),"\n",(0,s.jsxs)(n.p,{children:["Project consists of 2 source files - ",(0,s.jsx)(n.code,{children:"hangman.c"})," and ",(0,s.jsx)(n.code,{children:"main.c"}),"."]}),"\n",(0,s.jsxs)(n.p,{children:[(0,s.jsx)(n.code,{children:"main.c"})," is quite short and concise, there is nothing for you to do."]}),"\n",(0,s.jsxs)(n.p,{children:[(0,s.jsx)(n.code,{children:"hangman.c"})," contains implementation of the game. In case you feel lost, consult\nthe documentation in ",(0,s.jsx)(n.code,{children:"hangman.h"})," that represents an interface that can be used\nfor implementing the game."]}),"\n",(0,s.jsxs)(n.p,{children:["Apart from those sources this project is a bit more complicated. ",(0,s.jsx)(n.em,{children:"Game loop"})," is\nrealised via single encapsulated function that complicates the testing. Because\nof that, there are 2 kinds of tests:"]}),"\n",(0,s.jsxs)(n.ul,{children:["\n",(0,s.jsxs)(n.li,{children:["\n",(0,s.jsxs)(n.p,{children:[(0,s.jsx)(n.em,{children:"Unit tests"})," - that are present in ",(0,s.jsx)(n.code,{children:"test_hangman.c"})," and can be run via:"]}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{children:"$ make check-unit\n"})}),"\n",(0,s.jsx)(n.p,{children:"They cover majorly functions that can be tested easily via testing framework."}),"\n"]}),"\n",(0,s.jsxs)(n.li,{children:["\n",(0,s.jsxs)(n.p,{children:[(0,s.jsx)(n.em,{children:"Functional tests"})," - same as in ",(0,s.jsx)(n.code,{children:"seminar-08"})," and are focused on testing the\nprogram as whole. Basic smoke test is already included in ",(0,s.jsx)(n.code,{children:"usage"})," test case."]}),"\n",(0,s.jsx)(n.p,{children:"They can be run via:"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{children:"$ make check-functional\n"})}),"\n",(0,s.jsxs)(n.p,{children:["When testing ",(0,s.jsx)(n.code,{children:"hangman"})," function (the game loop), it is suggested to create\nfunctional tests."]}),"\n",(0,s.jsx)(n.p,{children:"When submitting the files for review, please leave out functional tests that\nwere given as a part of the assignment, so that it is easier to navigate, I\nwill drag the common files myself. :)"}),"\n"]}),"\n"]}),"\n",(0,s.jsxs)(n.blockquote,{children:["\n",(0,s.jsx)(n.p,{children:"Whole test suite can be run via:"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{children:"$ make check\n"})}),"\n"]}),"\n",(0,s.jsx)(n.h3,{id:"summary-of-the-gameplay",children:"Summary of the gameplay"}),"\n",(0,s.jsxs)(n.ol,{children:["\n",(0,s.jsx)(n.li,{children:"Secret word gets chosen from the file that's path is given as an argument."}),"\n",(0,s.jsx)(n.li,{children:"You get 8 guesses."}),"\n",(0,s.jsx)(n.li,{children:"Invalid characters don't count."}),"\n",(0,s.jsx)(n.li,{children:"Already guessed characters don't count, even if not included in the secret."}),"\n",(0,s.jsxs)(n.li,{children:["You can guess the whole word at once","\n",(0,s.jsxs)(n.ul,{children:["\n",(0,s.jsx)(n.li,{children:"If you get it right, you won, game ends."}),"\n",(0,s.jsx)(n.li,{children:"If you don't get it right, you get to see the secret, game ends."}),"\n"]}),"\n"]}),"\n",(0,s.jsx)(n.li,{children:"In case of end of input, game finishes via force."}),"\n",(0,s.jsx)(n.li,{children:"In case of invalid input, no guesses are subtracted, game carries on."}),"\n",(0,s.jsx)(n.li,{children:"Letters and words are not case sensitive."}),"\n"]}),"\n",(0,s.jsx)(n.h2,{id:"suggested-workflow",children:"Suggested workflow"}),"\n",(0,s.jsxs)(n.p,{children:["As we have talked about on the seminar, I suggest you to follow\n",(0,s.jsx)(n.em,{children:"Test-Driven Development"}),"\nin this case."]}),"\n",(0,s.jsx)(n.p,{children:(0,s.jsx)(n.img,{alt:"TDD workflow",src:t(27420).Z+"",width:"2814",height:"1652"})}),"\n",(0,s.jsx)(n.p,{children:"In our current scenario we are already in the stage of refactoring and fixing the\nbugs. Therefore try to follow this succession of steps:"}),"\n",(0,s.jsxs)(n.ol,{children:["\n",(0,s.jsx)(n.li,{children:"Try to reproduce the bug."}),"\n",(0,s.jsx)(n.li,{children:"Create a test that proves the presence of the bug."}),"\n",(0,s.jsx)(n.li,{children:"Fix the bug."}),"\n"]}),"\n",(0,s.jsxs)(n.p,{children:["In case you are submitting the bonus via GitLab, it is helpful to commit tests\nbefore commiting the fixes, so that it is apparent that the bug is manifested.\nExample of ",(0,s.jsx)(n.code,{children:"git log"})," (notice that the first line represents latest commit):"]}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{children:"feat: Implement fizz_buzzer\ntest: Add tests for fizz_buzzer\nfix: Fix NULL-check in print_name\ntest: Add test for NULL in print_name\n"})}),"\n",(0,s.jsx)(n.h2,{id:"tasks",children:"Tasks"}),"\n",(0,s.jsx)(n.p,{children:"As to your tasks, there are multiple things wrong in this project."}),"\n",(0,s.jsxs)(n.ol,{children:["\n",(0,s.jsxs)(n.li,{children:["\n",(0,s.jsx)(n.p,{children:'There are 2 "bugs" that cannot be detected via tests, i.e. they are not bugs\nthat affect functionality of the game.'}),"\n"]}),"\n",(0,s.jsxs)(n.li,{children:["\n",(0,s.jsxs)(n.p,{children:["There is one evil bug in ",(0,s.jsx)(n.code,{children:"get_word"}),". It is not required to be fixed ;) Assign\nit the lowest priority."]}),"\n"]}),"\n",(0,s.jsxs)(n.li,{children:["\n",(0,s.jsx)(n.p,{children:"There are some tests failing. Please try to figure it out, so you have green\ntests for the rest :)"}),"\n"]}),"\n",(0,s.jsxs)(n.li,{children:["\n",(0,s.jsxs)(n.p,{children:["We have gotten a bug report for ",(0,s.jsx)(n.code,{children:"word_guessed"}),", all we got is"]}),"\n",(0,s.jsxs)(n.blockquote,{children:["\n",(0,s.jsxs)(n.p,{children:["doesn't work when there are too many ",(0,s.jsx)(n.code,{children:"a"}),"s"]}),"\n"]}),"\n",(0,s.jsx)(n.p,{children:"Please try to replicate the bug and create a tests, so we don't get any\nregression later on."}),"\n"]}),"\n",(0,s.jsxs)(n.li,{children:["\n",(0,s.jsx)(n.p,{children:"One hidden bug :) Closely non-specified, we cannot reproduce it and we were\ndrunk while playing the game, so we don't remember a thing. :/"}),"\n"]}),"\n",(0,s.jsxs)(n.li,{children:["\n",(0,s.jsx)(n.p,{children:"Try to cover as much code via the tests as possible. We are not going to look\nat the metrics, but DRY is violated a lot, so as a last task try to remove as\nmuch of the duplicit code as possible."}),"\n",(0,s.jsx)(n.p,{children:"Tests should help you a lot in case there are some regressions."}),"\n"]}),"\n"]}),"\n",(0,s.jsx)(n.hr,{}),"\n",(0,s.jsxs)(n.p,{children:["In case you wonder why there are always 3 same words in the file with words, it\nis because of the ",(0,s.jsx)(n.code,{children:"get_word"})," bug. It is not a bug that can be easily fixed, so\nit is a not requirement at all and you can still get all points for the bonus ;)"]}),"\n",(0,s.jsx)(n.h2,{id:"dictionary",children:"Dictionary"}),"\n",(0,s.jsxs)(n.ul,{children:["\n",(0,s.jsx)(n.li,{children:(0,s.jsx)(n.a,{href:"https://en.wikipedia.org/wiki/Functional_testing",children:"Functional tests"})}),"\n",(0,s.jsx)(n.li,{children:(0,s.jsx)(n.a,{href:"https://en.wikipedia.org/wiki/Smoke_testing_%28software%29",children:"Smoke test"})}),"\n",(0,s.jsx)(n.li,{children:(0,s.jsx)(n.a,{href:"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself",children:"DRY"})}),"\n"]}),"\n",(0,s.jsx)(n.h2,{id:"submitting",children:"Submitting"}),"\n",(0,s.jsx)(n.p,{children:"In case you have any questions, feel free to reach out to me."}),"\n",(0,s.jsx)(n.hr,{})]})}function h(e={}){const{wrapper:n}={...(0,i.a)(),...e.components};return n?(0,s.jsx)(n,{...e,children:(0,s.jsx)(d,{...e})}):d(e)}},27420:(e,n,t)=>{t.d(n,{Z:()=>s});const s=t.p+"assets/images/tdd_lifecycle-327ad9ee0ed8318ed11e19a28e02b2cc.png"},11151:(e,n,t)=>{t.d(n,{Z:()=>a,a:()=>o});var s=t(67294);const i={},r=s.createContext(i);function o(e){const n=s.useContext(r);return s.useMemo((function(){return"function"==typeof e?e(n):{...n,...e}}),[n,e])}function a(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(i):e.components||i:o(e.components),s.createElement(r.Provider,{value:n},e.children)}}}]); \ No newline at end of file +"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[5376],{44969:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>o,default:()=>h,frontMatter:()=>r,metadata:()=>a,toc:()=>l});var s=t(85893),i=t(11151);const r={id:"seminar-10",title:"10th seminar",description:"Finding bugs in a hangman.\n"},o=void 0,a={id:"bonuses/seminar-10",title:"10th seminar",description:"Finding bugs in a hangman.\n",source:"@site/c/bonuses/10.md",sourceDirName:"bonuses",slug:"/bonuses/seminar-10",permalink:"/c/bonuses/seminar-10",draft:!1,unlisted:!1,editUrl:"https://github.com/mfocko/blog/tree/main/c/bonuses/10.md",tags:[],version:"current",lastUpdatedAt:1704558496,formattedLastUpdatedAt:"Jan 6, 2024",frontMatter:{id:"seminar-10",title:"10th seminar",description:"Finding bugs in a hangman.\n"},sidebar:"autogeneratedBar",previous:{title:"8th seminar",permalink:"/c/bonuses/seminar-08"},next:{title:"Practice Exams",permalink:"/c/category/practice-exams"}},c={},l=[{value:"Introduction",id:"introduction",level:2},{value:"Project",id:"project",level:2},{value:"Summary of the gameplay",id:"summary-of-the-gameplay",level:3},{value:"Suggested workflow",id:"suggested-workflow",level:2},{value:"Tasks",id:"tasks",level:2},{value:"Dictionary",id:"dictionary",level:2},{value:"Submitting",id:"submitting",level:2}];function d(e){const n={a:"a",blockquote:"blockquote",code:"code",em:"em",h2:"h2",h3:"h3",hr:"hr",img:"img",li:"li",ol:"ol",p:"p",pre:"pre",table:"table",tbody:"tbody",td:"td",th:"th",thead:"thead",tr:"tr",ul:"ul",...(0,i.a)(),...e.components};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(n.p,{children:(0,s.jsx)(n.a,{href:"pathname:///files/c/bonuses/10.tar.gz",children:"Source"})}),"\n",(0,s.jsx)(n.h2,{id:"introduction",children:"Introduction"}),"\n",(0,s.jsx)(n.p,{children:"For this bonus you are given almost finished project - The Hangman Game. Your\ntask is to try the game, in case you find any bugs point them out and cover as\nmuch of the game as possible with tests."}),"\n",(0,s.jsx)(n.p,{children:"For this bonus you can get at maximum 2 K\u20a1."}),"\n",(0,s.jsxs)(n.table,{children:[(0,s.jsx)(n.thead,{children:(0,s.jsxs)(n.tr,{children:[(0,s.jsx)(n.th,{children:"Item"}),(0,s.jsx)(n.th,{children:"Bonus"})]})}),(0,s.jsxs)(n.tbody,{children:[(0,s.jsxs)(n.tr,{children:[(0,s.jsx)(n.td,{children:"Fixing bugs from failing tests"}),(0,s.jsx)(n.td,{children:"0.25"})]}),(0,s.jsxs)(n.tr,{children:[(0,s.jsx)(n.td,{children:(0,s.jsx)(n.code,{children:"word_guessed"})}),(0,s.jsx)(n.td,{children:"0.50"})]}),(0,s.jsxs)(n.tr,{children:[(0,s.jsx)(n.td,{children:"Hidden bug"}),(0,s.jsx)(n.td,{children:"0.50"})]}),(0,s.jsxs)(n.tr,{children:[(0,s.jsx)(n.td,{children:"Extending tests, undetectable bugs or evil bug"}),(0,s.jsx)(n.td,{children:"0.37"})]}),(0,s.jsxs)(n.tr,{children:[(0,s.jsx)(n.td,{children:"Refactor"}),(0,s.jsx)(n.td,{children:"0.38"})]})]})]}),"\n",(0,s.jsx)(n.h2,{id:"project",children:"Project"}),"\n",(0,s.jsxs)(n.p,{children:["Project consists of 2 source files - ",(0,s.jsx)(n.code,{children:"hangman.c"})," and ",(0,s.jsx)(n.code,{children:"main.c"}),"."]}),"\n",(0,s.jsxs)(n.p,{children:[(0,s.jsx)(n.code,{children:"main.c"})," is quite short and concise, there is nothing for you to do."]}),"\n",(0,s.jsxs)(n.p,{children:[(0,s.jsx)(n.code,{children:"hangman.c"})," contains implementation of the game. In case you feel lost, consult\nthe documentation in ",(0,s.jsx)(n.code,{children:"hangman.h"})," that represents an interface that can be used\nfor implementing the game."]}),"\n",(0,s.jsxs)(n.p,{children:["Apart from those sources this project is a bit more complicated. ",(0,s.jsx)(n.em,{children:"Game loop"})," is\nrealised via single encapsulated function that complicates the testing. Because\nof that, there are 2 kinds of tests:"]}),"\n",(0,s.jsxs)(n.ul,{children:["\n",(0,s.jsxs)(n.li,{children:["\n",(0,s.jsxs)(n.p,{children:[(0,s.jsx)(n.em,{children:"Unit tests"})," - that are present in ",(0,s.jsx)(n.code,{children:"test_hangman.c"})," and can be run via:"]}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{children:"$ make check-unit\n"})}),"\n",(0,s.jsx)(n.p,{children:"They cover majorly functions that can be tested easily via testing framework."}),"\n"]}),"\n",(0,s.jsxs)(n.li,{children:["\n",(0,s.jsxs)(n.p,{children:[(0,s.jsx)(n.em,{children:"Functional tests"})," - same as in ",(0,s.jsx)(n.code,{children:"seminar-08"})," and are focused on testing the\nprogram as whole. Basic smoke test is already included in ",(0,s.jsx)(n.code,{children:"usage"})," test case."]}),"\n",(0,s.jsx)(n.p,{children:"They can be run via:"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{children:"$ make check-functional\n"})}),"\n",(0,s.jsxs)(n.p,{children:["When testing ",(0,s.jsx)(n.code,{children:"hangman"})," function (the game loop), it is suggested to create\nfunctional tests."]}),"\n",(0,s.jsx)(n.p,{children:"When submitting the files for review, please leave out functional tests that\nwere given as a part of the assignment, so that it is easier to navigate, I\nwill drag the common files myself. :)"}),"\n"]}),"\n"]}),"\n",(0,s.jsxs)(n.blockquote,{children:["\n",(0,s.jsx)(n.p,{children:"Whole test suite can be run via:"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{children:"$ make check\n"})}),"\n"]}),"\n",(0,s.jsx)(n.h3,{id:"summary-of-the-gameplay",children:"Summary of the gameplay"}),"\n",(0,s.jsxs)(n.ol,{children:["\n",(0,s.jsx)(n.li,{children:"Secret word gets chosen from the file that's path is given as an argument."}),"\n",(0,s.jsx)(n.li,{children:"You get 8 guesses."}),"\n",(0,s.jsx)(n.li,{children:"Invalid characters don't count."}),"\n",(0,s.jsx)(n.li,{children:"Already guessed characters don't count, even if not included in the secret."}),"\n",(0,s.jsxs)(n.li,{children:["You can guess the whole word at once","\n",(0,s.jsxs)(n.ul,{children:["\n",(0,s.jsx)(n.li,{children:"If you get it right, you won, game ends."}),"\n",(0,s.jsx)(n.li,{children:"If you don't get it right, you get to see the secret, game ends."}),"\n"]}),"\n"]}),"\n",(0,s.jsx)(n.li,{children:"In case of end of input, game finishes via force."}),"\n",(0,s.jsx)(n.li,{children:"In case of invalid input, no guesses are subtracted, game carries on."}),"\n",(0,s.jsx)(n.li,{children:"Letters and words are not case sensitive."}),"\n"]}),"\n",(0,s.jsx)(n.h2,{id:"suggested-workflow",children:"Suggested workflow"}),"\n",(0,s.jsxs)(n.p,{children:["As we have talked about on the seminar, I suggest you to follow\n",(0,s.jsx)(n.em,{children:"Test-Driven Development"}),"\nin this case."]}),"\n",(0,s.jsx)(n.p,{children:(0,s.jsx)(n.img,{alt:"TDD workflow",src:t(27420).Z+"",width:"2814",height:"1652"})}),"\n",(0,s.jsx)(n.p,{children:"In our current scenario we are already in the stage of refactoring and fixing the\nbugs. Therefore try to follow this succession of steps:"}),"\n",(0,s.jsxs)(n.ol,{children:["\n",(0,s.jsx)(n.li,{children:"Try to reproduce the bug."}),"\n",(0,s.jsx)(n.li,{children:"Create a test that proves the presence of the bug."}),"\n",(0,s.jsx)(n.li,{children:"Fix the bug."}),"\n"]}),"\n",(0,s.jsxs)(n.p,{children:["In case you are submitting the bonus via GitLab, it is helpful to commit tests\nbefore commiting the fixes, so that it is apparent that the bug is manifested.\nExample of ",(0,s.jsx)(n.code,{children:"git log"})," (notice that the first line represents latest commit):"]}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{children:"feat: Implement fizz_buzzer\ntest: Add tests for fizz_buzzer\nfix: Fix NULL-check in print_name\ntest: Add test for NULL in print_name\n"})}),"\n",(0,s.jsx)(n.h2,{id:"tasks",children:"Tasks"}),"\n",(0,s.jsx)(n.p,{children:"As to your tasks, there are multiple things wrong in this project."}),"\n",(0,s.jsxs)(n.ol,{children:["\n",(0,s.jsxs)(n.li,{children:["\n",(0,s.jsx)(n.p,{children:'There are 2 "bugs" that cannot be detected via tests, i.e. they are not bugs\nthat affect functionality of the game.'}),"\n"]}),"\n",(0,s.jsxs)(n.li,{children:["\n",(0,s.jsxs)(n.p,{children:["There is one evil bug in ",(0,s.jsx)(n.code,{children:"get_word"}),". It is not required to be fixed ;) Assign\nit the lowest priority."]}),"\n"]}),"\n",(0,s.jsxs)(n.li,{children:["\n",(0,s.jsx)(n.p,{children:"There are some tests failing. Please try to figure it out, so you have green\ntests for the rest :)"}),"\n"]}),"\n",(0,s.jsxs)(n.li,{children:["\n",(0,s.jsxs)(n.p,{children:["We have gotten a bug report for ",(0,s.jsx)(n.code,{children:"word_guessed"}),", all we got is"]}),"\n",(0,s.jsxs)(n.blockquote,{children:["\n",(0,s.jsxs)(n.p,{children:["doesn't work when there are too many ",(0,s.jsx)(n.code,{children:"a"}),"s"]}),"\n"]}),"\n",(0,s.jsx)(n.p,{children:"Please try to replicate the bug and create a tests, so we don't get any\nregression later on."}),"\n"]}),"\n",(0,s.jsxs)(n.li,{children:["\n",(0,s.jsx)(n.p,{children:"One hidden bug :) Closely non-specified, we cannot reproduce it and we were\ndrunk while playing the game, so we don't remember a thing. :/"}),"\n"]}),"\n",(0,s.jsxs)(n.li,{children:["\n",(0,s.jsx)(n.p,{children:"Try to cover as much code via the tests as possible. We are not going to look\nat the metrics, but DRY is violated a lot, so as a last task try to remove as\nmuch of the duplicit code as possible."}),"\n",(0,s.jsx)(n.p,{children:"Tests should help you a lot in case there are some regressions."}),"\n"]}),"\n"]}),"\n",(0,s.jsx)(n.hr,{}),"\n",(0,s.jsxs)(n.p,{children:["In case you wonder why there are always 3 same words in the file with words, it\nis because of the ",(0,s.jsx)(n.code,{children:"get_word"})," bug. It is not a bug that can be easily fixed, so\nit is a not requirement at all and you can still get all points for the bonus ;)"]}),"\n",(0,s.jsx)(n.h2,{id:"dictionary",children:"Dictionary"}),"\n",(0,s.jsxs)(n.ul,{children:["\n",(0,s.jsx)(n.li,{children:(0,s.jsx)(n.a,{href:"https://en.wikipedia.org/wiki/Functional_testing",children:"Functional tests"})}),"\n",(0,s.jsx)(n.li,{children:(0,s.jsx)(n.a,{href:"https://en.wikipedia.org/wiki/Smoke_testing_%28software%29",children:"Smoke test"})}),"\n",(0,s.jsx)(n.li,{children:(0,s.jsx)(n.a,{href:"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself",children:"DRY"})}),"\n"]}),"\n",(0,s.jsx)(n.h2,{id:"submitting",children:"Submitting"}),"\n",(0,s.jsx)(n.p,{children:"In case you have any questions, feel free to reach out to me."}),"\n",(0,s.jsx)(n.hr,{})]})}function h(e={}){const{wrapper:n}={...(0,i.a)(),...e.components};return n?(0,s.jsx)(n,{...e,children:(0,s.jsx)(d,{...e})}):d(e)}},27420:(e,n,t)=>{t.d(n,{Z:()=>s});const s=t.p+"assets/images/tdd_lifecycle-327ad9ee0ed8318ed11e19a28e02b2cc.png"},11151:(e,n,t)=>{t.d(n,{Z:()=>a,a:()=>o});var s=t(67294);const i={},r=s.createContext(i);function o(e){const n=s.useContext(r);return s.useMemo((function(){return"function"==typeof e?e(n):{...n,...e}}),[n,e])}function a(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(i):e.components||i:o(e.components),s.createElement(r.Provider,{value:n},e.children)}}}]); \ No newline at end of file diff --git a/assets/js/22a175ec.504e3826.js b/assets/js/22a175ec.92356088.js similarity index 62% rename from assets/js/22a175ec.504e3826.js rename to assets/js/22a175ec.92356088.js index b5e67ec..f4a9070 100644 --- a/assets/js/22a175ec.504e3826.js +++ b/assets/js/22a175ec.92356088.js @@ -1 +1 @@ -"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[6890],{40707:(e,t,i)=>{i.r(t),i.d(t,{default:()=>x});var r=i(67294),o=i(80647),s=i(86010);const n="card_n_Wj",a="contributionsContainer_vdAK",l="buttons_UAd1";var c,h;function d(){return d=Object.assign?Object.assign.bind():function(e){for(var t=1;t{let{title:t,titleId:i,...o}=e;return r.createElement("svg",d({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24","aria-labelledby":i},o),t?r.createElement("title",{id:i},t):null,c||(c=r.createElement("path",{fill:"none",d:"M0 0h24v24H0z"})),h||(h=r.createElement("path",{d:"M13 21v2.5l-3-2-3 2V21h-.5A3.5 3.5 0 0 1 3 17.5V5a3 3 0 0 1 3-3h14a1 1 0 0 1 1 1v17a1 1 0 0 1-1 1h-7zm0-2h6v-3H6.5a1.5 1.5 0 0 0 0 3H7v-2h6v2zm6-5V4H6v10.035A3.53 3.53 0 0 1 6.5 14H19zM7 5h2v2H7V5zm0 3h2v2H7V8zm0 3h2v2H7v-2z"})))};var u=i(85893);const b=e=>{let{title:t,description:i,contribution:r,repoURL:o}=e;return(0,u.jsx)("div",{className:"col col--12",children:(0,u.jsxs)("div",{className:(0,s.Z)("card",n),children:[(0,u.jsx)("div",{className:"card__header",children:(0,u.jsx)("h2",{children:t})}),(0,u.jsx)("div",{className:"card__body",children:(0,u.jsxs)("div",{className:"row",children:[(0,u.jsxs)("div",{className:"col col--6",children:[(0,u.jsx)("h6",{children:"Description"}),i]}),(0,u.jsxs)("div",{className:(0,s.Z)("col col--6",a),children:[(0,u.jsx)("h6",{children:"Contribution"}),r]})]})}),(0,u.jsx)("div",{className:"card__footer",children:(0,u.jsx)("div",{className:l,children:(0,u.jsxs)("a",{href:o,target:"_blank",className:"button button--secondary button--outline",children:[(0,u.jsx)("span",{className:"button__icon",children:(0,u.jsx)(p,{})}),"See repository"]})})})]})})},g=[{title:"tmt",description:(0,u.jsx)("p",{children:"The `tmt` tool provides a user-friendly way to work with tests. You can comfortably create new tests, safely and easily run tests across different environments, review test results, debug test code and enable tests in the CI using a consistent and concise config."}),contribution:(0,u.jsx)("p",{children:"Just a smallish contribution to the docs related to the changes implemented on the Packit side."}),repoURL:"https://github.com/teemtee/tmt"},{title:"Fedora Infrastructure Ansible",description:(0,u.jsx)("p",{children:"Collection of Ansible playbooks that powers the Fedora Infrastructure."}),contribution:(0,u.jsx)("p",{children:"I have adjusted the groups in the Bodhi playbooks after Packit has been granted the privileges to propose updates without restrictions."}),repoURL:"https://pagure.io/fedora-infra/ansible"},{title:"Bodhi",description:(0,u.jsx)("p",{children:"Bodhi is a web-system that facilitates the process of publishing updates for a Fedora-based software distribution."}),contribution:(0,u.jsx)("p",{children:"I have adjusted the client, so that it doesn't show secrets in terminal when you log in to the Bodhi via browser."}),repoURL:"https://github.com/fedora-infra/bodhi"},{title:"Gluetool Modules Collection",description:(0,u.jsxs)("p",{children:["Modules for ",(0,u.jsx)("code",{children:"gluetool"})," \u2014 a command line centric framework usable for glueing modules into a pipeline."]}),contribution:(0,u.jsxs)("ul",{children:[(0,u.jsx)("li",{children:"I have proposed a possible implementation of git merging that was later on extended."}),(0,u.jsx)("li",{children:"I have tried to help out with Copr module after they deprecated older version of their API."})]}),repoURL:"https://gitlab.com/testing-farm/gluetool-modules"},{title:"Pagure",description:(0,u.jsx)("p",{children:"Pagure is a git-centered forge, python based using pygit2."}),contribution:(0,u.jsx)("p",{children:"I have added an API endpoint for reopening pull requests."}),repoURL:"https://pagure.io/pagure"},{title:"Copr",description:(0,u.jsxs)("p",{children:["RPM build system - upstream for"," ",(0,u.jsx)("a",{target:"_blank",href:"https://copr.fedorainfracloud.org/",children:"Copr"}),"."]}),contribution:(0,u.jsxs)("ul",{children:[(0,u.jsx)("li",{children:"Supporting external repositories for custom SRPM build method."}),(0,u.jsxs)("li",{children:["Allowing admins of Copr repositories to build without the need to ask for explicit ",(0,u.jsx)("code",{children:"builder"})," permissions."]})]}),repoURL:"https://github.com/fedora-copr/copr"},{title:"python-gitlab",description:(0,u.jsx)("p",{children:"A python wrapper for the GitLab API."}),contribution:(0,u.jsxs)("p",{children:["I have contributed support for the ",(0,u.jsx)("code",{children:"merge_ref"})," on merge requests that hasn't been supported, yet it was present in the GitLab API."]}),repoURL:"https://github.com/python-gitlab/python-gitlab"},{title:"PatternFly React",description:(0,u.jsx)("p",{children:"A set of React components for the PatternFly project."}),contribution:(0,u.jsx)("p",{children:"When working on Packit Dashboard, I have spotted smaller bugs that were present in this project and fixed them upstream to provide better experience for our users."}),repoURL:"https://github.com/patternfly/patternfly-react"},{title:"Fira Code",description:(0,u.jsx)("p",{children:"Free monospaced font with programming ligatures."}),contribution:(0,u.jsxs)("p",{children:["I have set up a GitHub Action for building the font on each push to the default branch allowing users to install ",(0,u.jsx)("i",{children:"bleeding edge"})," ","version of the font."]}),repoURL:"https://github.com/tonsky/FiraCode"},{title:"nixpkgs",description:(0,u.jsx)("p",{children:"Nixpkgs is a collection of over 80,000 software packages that can be installed with the Nix package manager. It also implements NixOS, a purely-functional Linux distribution."}),contribution:(0,u.jsx)("p",{children:"When I was trying out the nixpkgs, I have tried to bump .NET Core to the latest version. My changes haven't been accepted as they required bumping of multiple more packages that depended upon the .NET Core."}),repoURL:"https://github.com/NixOS/nixpkgs"},{title:"Darcula",description:(0,u.jsx)("p",{children:"A theme for Visual Studio Code based on Darcula theme from Jetbrains IDEs."}),contribution:(0,u.jsx)("p",{children:"I have contributed support for diff files, though the project doesn't seem to be live anymore, so it hasn't been accepted as of now."}),repoURL:"https://github.com/rokoroku/vscode-theme-darcula"},{title:"Packit",description:(0,u.jsx)("p",{children:"An open source project aiming to ease the integration of your project with Fedora Linux, CentOS Stream and other distributions."}),contribution:(0,u.jsxs)("p",{children:["Have a look at my"," ",(0,u.jsx)("a",{href:"https://github.com/search?q=is%3Apr%20author%3Amfocko%20org%3Apackit&type=pullrequests",target:"_blank",children:"pull requests"}),"."]}),repoURL:"https://github.com/packit"},{title:"Snitch",description:(0,u.jsx)(u.Fragment,{children:(0,u.jsx)("p",{children:"Language agnostic tool that collects TODOs in the source code and reports them as Issues."})}),contribution:(0,u.jsxs)("ul",{children:[(0,u.jsx)("li",{children:"Environment variable support for self-hosted GitLab instances"}),(0,u.jsx)("li",{children:"GitLab support"})]}),repoURL:"https://github.com/tsoding/snitch"},{title:"Karel the Robot",description:(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)("p",{children:["Karel the robot is in general an educational programming language for beginners, created by ",(0,u.jsx)("i",{children:"Richard E. Pattis"}),". This is implementation of ",(0,u.jsx)("i",{children:"Karel the Robot"})," for"," ",(0,u.jsx)("i",{children:"C programming language"}),"."]}),(0,u.jsxs)("p",{children:["This project is used for educational purposes at"," ",(0,u.jsx)("a",{target:"_blank",href:"https://fei.tuke.sk",children:"TUKE"}),"."]})]}),contribution:(0,u.jsx)("p",{children:"I have contributed some refactoring tips to the author of the library."}),repoURL:"https://git.kpi.fei.tuke.sk/kpi/karel-the-robot"}],m="Contributions",f="Many of my contributions to open-source projects.";function x(){return(0,u.jsx)(o.Z,{title:m,description:f,children:(0,u.jsxs)("main",{className:"container container--fluid margin-vert--lg",children:[(0,u.jsx)("h1",{children:m}),(0,u.jsx)("p",{children:f}),(0,u.jsx)("div",{className:"row",children:g.map((e=>(0,u.jsx)(b,{...e},e.project)))})]})})}},86010:(e,t,i)=>{function r(e){var t,i,o="";if("string"==typeof e||"number"==typeof e)o+=e;else if("object"==typeof e)if(Array.isArray(e))for(t=0;to});const o=function(){for(var e,t,i=0,o="";i{i.r(t),i.d(t,{default:()=>x});var r=i(67294),o=i(80647),s=i(86010);const n="card_n_Wj",a="contributionsContainer_vdAK",l="buttons_UAd1";var c,h;function d(){return d=Object.assign?Object.assign.bind():function(e){for(var t=1;t{let{title:t,titleId:i,...o}=e;return r.createElement("svg",d({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24","aria-labelledby":i},o),t?r.createElement("title",{id:i},t):null,c||(c=r.createElement("path",{fill:"none",d:"M0 0h24v24H0z"})),h||(h=r.createElement("path",{d:"M13 21v2.5l-3-2-3 2V21h-.5A3.5 3.5 0 0 1 3 17.5V5a3 3 0 0 1 3-3h14a1 1 0 0 1 1 1v17a1 1 0 0 1-1 1h-7zm0-2h6v-3H6.5a1.5 1.5 0 0 0 0 3H7v-2h6v2zm6-5V4H6v10.035A3.53 3.53 0 0 1 6.5 14H19zM7 5h2v2H7V5zm0 3h2v2H7V8zm0 3h2v2H7v-2z"})))};var u=i(85893);const b=e=>{let{title:t,description:i,contribution:r,repoURL:o}=e;return(0,u.jsx)("div",{className:"col col--12",children:(0,u.jsxs)("div",{className:(0,s.Z)("card",n),children:[(0,u.jsx)("div",{className:"card__header",children:(0,u.jsx)("h2",{children:t})}),(0,u.jsx)("div",{className:"card__body",children:(0,u.jsxs)("div",{className:"row",children:[(0,u.jsxs)("div",{className:"col col--6",children:[(0,u.jsx)("h6",{children:"Description"}),i]}),(0,u.jsxs)("div",{className:(0,s.Z)("col col--6",a),children:[(0,u.jsx)("h6",{children:"Contribution"}),r]})]})}),(0,u.jsx)("div",{className:"card__footer",children:(0,u.jsx)("div",{className:l,children:(0,u.jsxs)("a",{href:o,target:"_blank",className:"button button--secondary button--outline",children:[(0,u.jsx)("span",{className:"button__icon",children:(0,u.jsx)(p,{})}),"See repository"]})})})]})})},g=[{title:"tmt",description:(0,u.jsx)("p",{children:"The `tmt` tool provides a user-friendly way to work with tests. You can comfortably create new tests, safely and easily run tests across different environments, review test results, debug test code and enable tests in the CI using a consistent and concise config."}),contribution:(0,u.jsx)("p",{children:"Just a smallish contribution to the docs related to the changes implemented on the Packit side."}),repoURL:"https://github.com/teemtee/tmt"},{title:"Fedora Infrastructure Ansible",description:(0,u.jsx)("p",{children:"Collection of Ansible playbooks that powers the Fedora Infrastructure."}),contribution:(0,u.jsx)("p",{children:"I have adjusted the groups in the Bodhi playbooks after Packit has been granted the privileges to propose updates without restrictions."}),repoURL:"https://pagure.io/fedora-infra/ansible"},{title:"Bodhi",description:(0,u.jsx)("p",{children:"Bodhi is a web-system that facilitates the process of publishing updates for a Fedora-based software distribution."}),contribution:(0,u.jsx)("p",{children:"I have adjusted the client, so that it doesn't show secrets in terminal when you log in to the Bodhi via browser."}),repoURL:"https://github.com/fedora-infra/bodhi"},{title:"Gluetool Modules Collection",description:(0,u.jsxs)("p",{children:["Modules for ",(0,u.jsx)("code",{children:"gluetool"})," \u2014 a command line centric framework usable for glueing modules into a pipeline."]}),contribution:(0,u.jsxs)("ul",{children:[(0,u.jsx)("li",{children:"I have proposed a possible implementation of git merging that was later on extended."}),(0,u.jsx)("li",{children:"I have tried to help out with Copr module after they deprecated older version of their API."})]}),repoURL:"https://gitlab.com/testing-farm/gluetool-modules"},{title:"Pagure",description:(0,u.jsx)("p",{children:"Pagure is a git-centered forge, python based using pygit2."}),contribution:(0,u.jsx)("p",{children:"I have added an API endpoint for reopening pull requests."}),repoURL:"https://pagure.io/pagure"},{title:"Copr",description:(0,u.jsxs)("p",{children:["RPM build system - upstream for"," ",(0,u.jsx)("a",{target:"_blank",href:"https://copr.fedorainfracloud.org/",children:"Copr"}),"."]}),contribution:(0,u.jsxs)("ul",{children:[(0,u.jsx)("li",{children:"Supporting external repositories for custom SRPM build method."}),(0,u.jsxs)("li",{children:["Allowing admins of Copr repositories to build without the need to ask for explicit ",(0,u.jsx)("code",{children:"builder"})," permissions."]})]}),repoURL:"https://github.com/fedora-copr/copr"},{title:"python-gitlab",description:(0,u.jsx)("p",{children:"A python wrapper for the GitLab API."}),contribution:(0,u.jsxs)("p",{children:["I have contributed support for the ",(0,u.jsx)("code",{children:"merge_ref"})," on merge requests that hasn't been supported, yet it was present in the GitLab API."]}),repoURL:"https://github.com/python-gitlab/python-gitlab"},{title:"PatternFly React",description:(0,u.jsx)("p",{children:"A set of React components for the PatternFly project."}),contribution:(0,u.jsx)("p",{children:"When working on Packit Dashboard, I have spotted smaller bugs that were present in this project and fixed them upstream to provide better experience for our users."}),repoURL:"https://github.com/patternfly/patternfly-react"},{title:"Fira Code",description:(0,u.jsx)("p",{children:"Free monospaced font with programming ligatures."}),contribution:(0,u.jsxs)("p",{children:["I have set up a GitHub Action for building the font on each push to the default branch allowing users to install ",(0,u.jsx)("i",{children:"bleeding edge"})," version of the font."]}),repoURL:"https://github.com/tonsky/FiraCode"},{title:"nixpkgs",description:(0,u.jsx)("p",{children:"Nixpkgs is a collection of over 80,000 software packages that can be installed with the Nix package manager. It also implements NixOS, a purely-functional Linux distribution."}),contribution:(0,u.jsx)("p",{children:"When I was trying out the nixpkgs, I have tried to bump .NET Core to the latest version. My changes haven't been accepted as they required bumping of multiple more packages that depended upon the .NET Core."}),repoURL:"https://github.com/NixOS/nixpkgs"},{title:"Darcula",description:(0,u.jsx)("p",{children:"A theme for Visual Studio Code based on Darcula theme from Jetbrains IDEs."}),contribution:(0,u.jsx)("p",{children:"I have contributed support for diff files, though the project doesn't seem to be live anymore, so it hasn't been accepted as of now."}),repoURL:"https://github.com/rokoroku/vscode-theme-darcula"},{title:"Packit",description:(0,u.jsx)("p",{children:"An open source project aiming to ease the integration of your project with Fedora Linux, CentOS Stream and other distributions."}),contribution:(0,u.jsxs)("p",{children:["Have a look at my"," ",(0,u.jsx)("a",{href:"https://github.com/search?q=is%3Apr%20author%3Amfocko%20org%3Apackit&type=pullrequests",target:"_blank",children:"pull requests"}),"."]}),repoURL:"https://github.com/packit"},{title:"Snitch",description:(0,u.jsx)(u.Fragment,{children:(0,u.jsx)("p",{children:"Language agnostic tool that collects TODOs in the source code and reports them as Issues."})}),contribution:(0,u.jsxs)("ul",{children:[(0,u.jsx)("li",{children:"Environment variable support for self-hosted GitLab instances"}),(0,u.jsx)("li",{children:"GitLab support"})]}),repoURL:"https://github.com/tsoding/snitch"},{title:"Karel the Robot",description:(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)("p",{children:["Karel the robot is in general an educational programming language for beginners, created by ",(0,u.jsx)("i",{children:"Richard E. Pattis"}),". This is implementation of ",(0,u.jsx)("i",{children:"Karel the Robot"})," for ",(0,u.jsx)("i",{children:"C programming language"}),"."]}),(0,u.jsxs)("p",{children:["This project is used for educational purposes at"," ",(0,u.jsx)("a",{target:"_blank",href:"https://fei.tuke.sk",children:"TUKE"}),"."]})]}),contribution:(0,u.jsx)("p",{children:"I have contributed some refactoring tips to the author of the library."}),repoURL:"https://git.kpi.fei.tuke.sk/kpi/karel-the-robot"}],m="Contributions",f="Many of my contributions to open-source projects.";function x(){return(0,u.jsx)(o.Z,{title:m,description:f,children:(0,u.jsxs)("main",{className:"container container--fluid margin-vert--lg",children:[(0,u.jsx)("h1",{children:m}),(0,u.jsx)("p",{children:f}),(0,u.jsx)("div",{className:"row",children:g.map((e=>(0,u.jsx)(b,{...e},e.project)))})]})})}},86010:(e,t,i)=>{function r(e){var t,i,o="";if("string"==typeof e||"number"==typeof e)o+=e;else if("object"==typeof e)if(Array.isArray(e))for(t=0;to});const o=function(){for(var e,t,i=0,o="";i{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>o,default:()=>h,frontMatter:()=>r,metadata:()=>a,toc:()=>l});var i=t(85893),s=t(11151);const r={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:!1},o=void 0,a={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:!0,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:!1},unlisted:!1,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"}},d={authorsImageUrls:[void 0]},l=[{value:"Day 8: Treetop Tree House",id:"day-8-treetop-tree-house",level:2},{value:"Swapping indices",id:"swapping-indices",level:4},{value:"Indexing Vec",id:"indexing-vec",level:4},{value:"Issues",id:"issues",level:5},{value:"Checking bounds",id:"checking-bounds",level:4},{value:"Solution",id:"solution",level:3},{value:"Day 9: Rope Bridge",id:"day-9-rope-bridge",level:2},{value:"Solution",id:"solution-1",level:3},{value:"Day 10: Cathode-Ray Tube",id:"day-10-cathode-ray-tube",level:2},{value:"What does that mean though?",id:"what-does-that-mean-though",level:6},{value:"Solution",id:"solution-2",level:3},{value:"Day 11: Monkey in the Middle",id:"day-11-monkey-in-the-middle",level:2},{value:"Solution",id:"solution-3",level:3},{value:"Day 12: Hill Climbing Algorithm",id:"day-12-hill-climbing-algorithm",level:2},{value:"Solution",id:"solution-4",level:3},{value:"Day 13: Distress Signal",id:"day-13-distress-signal",level:2},{value:"Solution",id:"solution-5",level:3},{value:"Day 14: Regolith Reservoir",id:"day-14-regolith-reservoir",level:2},{value:"Solution",id:"solution-6",level:3},{value:"Post Mortem",id:"post-mortem",level:2},{value:"Indexing",id:"indexing",level:3},{value:"Cause of the problem",id:"cause-of-the-problem",level:4}];function c(e){const n={a:"a",admonition:"admonition",annotation:"annotation",blockquote:"blockquote",code:"code",em:"em",h2:"h2",h3:"h3",h4:"h4",h5:"h5",h6:"h6",li:"li",math:"math",mdxAdmonitionTitle:"mdxAdmonitionTitle",mi:"mi",mn:"mn",mo:"mo",mrow:"mrow",p:"p",pre:"pre",semantics:"semantics",span:"span",strong:"strong",ul:"ul",...(0,s.a)(),...e.components};return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)(n.p,{children:["Let's go through the second week of ",(0,i.jsx)(n.a,{href:"https://adventofcode.com",children:(0,i.jsx)(n.em,{children:"Advent of Code"})})," in Rust."]}),"\n",(0,i.jsx)(n.h2,{id:"day-8-treetop-tree-house",children:(0,i.jsx)(n.a,{href:"https://adventofcode.com/2022/day/8",children:"Day 8: Treetop Tree House"})}),"\n",(0,i.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(n.p,{children:"We 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",(0,i.jsxs)(n.p,{children:["Nothing 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 ",(0,i.jsx)(n.code,{children:"Vector2D"})," and now it's time to extend it with indexing\nof ",(0,i.jsx)(n.code,{children:"Vec"})," of ",(0,i.jsx)(n.code,{children:"Vec"}),"s. In my solution I was manipulating with indices in the following\nway:"]}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsx)(n.li,{children:"swapping them"}),"\n",(0,i.jsxs)(n.li,{children:["checking whether they are correct indices for the ",(0,i.jsx)(n.code,{children:"Vec>"})]}),"\n",(0,i.jsxs)(n.li,{children:["indexing ",(0,i.jsx)(n.code,{children:"Vec>"})," with them"]}),"\n"]}),"\n",(0,i.jsx)(n.admonition,{type:"caution",children:(0,i.jsxs)(n.p,{children:["I'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 ",(0,i.jsx)(n.em,{children:"thicc"})," ",(0,i.jsx)(n.strong,{children:"\xab\u21af\xbb"})," mark and will try to \u201clock\u201d them into their\nown \u201cbox of hell\u201d."]})}),"\n",(0,i.jsx)(n.h4,{id:"swapping-indices",children:"Swapping indices"}),"\n",(0,i.jsx)(n.p,{children:"Relatively simple implementation, just take the values, swap them and return new\nvector."}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"impl Vector2D {\n pub fn swap(&self) -> Self {\n Self {\n x: self.y,\n y: self.x,\n }\n }\n}\n"})}),"\n",(0,i.jsxs)(n.p,{children:["Pretty straight-forward implementation, but let's talk about the ",(0,i.jsx)(n.code,{children:"T: Copy"}),". We\nneed to use it, since we are returning a ",(0,i.jsx)(n.strong,{children:"new"})," vector, with swapped ",(0,i.jsx)(n.strong,{children:"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",(0,i.jsxs)(n.h4,{id:"indexing-vec",children:["Indexing ",(0,i.jsx)(n.code,{children:"Vec"})]}),"\n",(0,i.jsx)(n.p,{children:"I will start with the indexing, cause bound-checking is a bit more\u2026 complicated\nthan I would like to."}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"pub fn index<'a, T, U>(v: &'a [Vec], idx: &Vector2D) -> &'a U\nwhere\n usize: TryFrom,\n >::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",(0,i.jsxs)(n.p,{children:["Let'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 ",(0,i.jsx)(n.code,{children:"x"})," and ",(0,i.jsx)(n.code,{children:"y"})," and convert\nthem both to ",(0,i.jsx)(n.code,{children:"usize"})," type that can be used later on for indexing."]}),"\n",(0,i.jsxs)(n.p,{children:["The type signature of the function is where the fun is at ","\ud83d\ude09"," We are trying\nto convert unknown type to ",(0,i.jsx)(n.code,{children:"usize"}),", so we must bound the ",(0,i.jsx)(n.code,{children:"T"})," as a type that can\nbe converted to ",(0,i.jsx)(n.code,{children:"usize"}),", that's how we got ",(0,i.jsx)(n.code,{children:"usize: TryFrom"})," which basically\nsays that ",(0,i.jsx)(n.code,{children:"usize"})," must implement ",(0,i.jsx)(n.code,{children:"TryFrom"})," trait and therefore allows us to\nconvert the indices to actual ",(0,i.jsx)(n.code,{children:"usize"})," indices. Using ",(0,i.jsx)(n.code,{children:".unwrap()"})," also forces us\nto bound the error that can occur when converting ",(0,i.jsx)(n.code,{children:"T"})," into ",(0,i.jsx)(n.code,{children:"usize"}),", that's how\nwe get ",(0,i.jsx)(n.code,{children:">::Error: Debug"})," which loosely means"]}),"\n",(0,i.jsxs)(n.blockquote,{children:["\n",(0,i.jsxs)(n.p,{children:["error during conversion of ",(0,i.jsx)(n.code,{children:"T"})," into ",(0,i.jsx)(n.code,{children:"usize"})," must implement ",(0,i.jsx)(n.code,{children:"Debug"}),",\ni.e. can be printed in some way or other"]}),"\n"]}),"\n",(0,i.jsxs)(n.p,{children:[(0,i.jsx)(n.code,{children:"T: Copy"})," is required by ",(0,i.jsx)(n.code,{children:".try_into()"})," which takes ",(0,i.jsx)(n.code,{children:"T"})," by-value."]}),"\n",(0,i.jsx)(n.p,{children:"And now we are left only with the first line of the definition."}),"\n",(0,i.jsx)(n.admonition,{type:"note",children:(0,i.jsx)(n.p,{children:"Skilled 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",(0,i.jsx)(n.p,{children:"Let's split it in multiple parts:"}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"v: &'a [Vec]"})," represents the 2D ",(0,i.jsx)(n.code,{children:"Vec"}),", we are indexing, ",(0,i.jsx)(n.code,{children:"Vec"})," implements\n",(0,i.jsx)(n.code,{children:"Slice"})," trait and ",(0,i.jsx)(n.em,{children:"clippy"})," recommends using ",(0,i.jsx)(n.code,{children:"&[T]"})," to ",(0,i.jsx)(n.code,{children:"&Vec"}),", exact details\nare unknown to me"]}),"\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"idx: &Vector2D"})," represents the ",(0,i.jsx)(n.em,{children:"indices"})," which we use, we take them by\nreference to avoid an unnecessary copy"]}),"\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"-> &'a U"})," means that we are returning a ",(0,i.jsx)(n.em,{children:"reference"})," to some value of type ",(0,i.jsx)(n.code,{children:"U"}),".\nNow the question is what does the ",(0,i.jsx)(n.code,{children:"'a"})," mean, we can also see it as a generic\ntype declared along ",(0,i.jsx)(n.code,{children:"T"})," and ",(0,i.jsx)(n.code,{children:"U"}),". And the answer is ",(0,i.jsx)(n.em,{children:"relatively"})," simple, ",(0,i.jsx)(n.code,{children:"'a"}),"\nrepresents a ",(0,i.jsx)(n.em,{children:"lifetime"}),". We take the ",(0,i.jsx)(n.code,{children:"v"})," by a reference and return a reference,\nborrow checker validates all of the ",(0,i.jsx)(n.em,{children:"borrows"})," (or references), so we need to\nspecify that our returned value has ",(0,i.jsx)(n.em,{children:"the same lifetime"})," as the vector we have\ntaken by a reference, i.e. returned reference must live at least as long as the\n",(0,i.jsx)(n.code,{children:"v"}),". This way we can \u201cbe sure\u201d that the returned reference is valid."]}),"\n"]}),"\n",(0,i.jsx)(n.h5,{id:"issues",children:"Issues"}),"\n",(0,i.jsxs)(n.p,{children:["First 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. ",(0,i.jsx)(n.code,{children:"index_mut"}),". Which I have actually done while writing this part:"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"pub fn index_mut<'a, T, U>(v: &'a mut [Vec], idx: &Vector2D) -> &'a mut U\nwhere\n usize: TryFrom,\n >::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",(0,i.jsxs)(n.admonition,{type:"caution",children:[(0,i.jsxs)(n.mdxAdmonitionTitle,{children:[(0,i.jsx)(n.strong,{children:"\xab\u21af\xbb"})," Why can't we use one function?"]}),(0,i.jsxs)(n.p,{children:["When we consider a ",(0,i.jsx)(n.code,{children:"Vec"}),", we don't need to consider containers as ",(0,i.jsx)(n.code,{children:"T"}),", Rust\nimplements indexing as traits ",(0,i.jsx)(n.code,{children:"Index"})," and ",(0,i.jsx)(n.code,{children:"IndexMut"})," that do the dirty work\nbehind syntactic sugar of ",(0,i.jsx)(n.code,{children:"container[idx]"}),"."]}),(0,i.jsxs)(n.p,{children:["However, implementing of traits is not allowed for ",(0,i.jsx)(n.em,{children:"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."]}),(0,i.jsxs)(n.p,{children:["Another part of this rabbit hole is trait ",(0,i.jsx)(n.code,{children:"SliceIndex"})," that is of a relevance\nbecause of"]}),(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"impl Index for [T]\nwhere\n I: SliceIndex<[T]>\n\nimpl Index for Vec\nwhere\n I: SliceIndex<[T]>,\n A: Allocator\n\nimpl Index for [T; N]\nwhere\n [T]: Index\n"})}),(0,i.jsxs)(n.p,{children:["In other words, if your type implements ",(0,i.jsx)(n.code,{children:"SliceIndex"})," trait, it can be used\nfor indexing. As of now, this trait has all of its required methods experimental\nand is marked as ",(0,i.jsx)(n.code,{children:"unsafe"}),"."]})]}),"\n",(0,i.jsxs)(n.p,{children:["Another problem is a requirement for indexing either ",(0,i.jsx)(n.code,{children:"[Vec]"})," or ",(0,i.jsx)(n.code,{children:"Vec>"}),".\nThis requirement could be countered by removing inner type ",(0,i.jsx)(n.code,{children:"Vec"})," and constraining\nit by a trait ",(0,i.jsx)(n.code,{children:"Index"})," (or ",(0,i.jsx)(n.code,{children:"IndexMut"})," respectively) in a following way"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"pub fn index<'a, C, T>(v: &'a [C], idx: &Vector2D) -> &'a C::Output\nwhere\n usize: TryFrom,\n >::Error: Debug,\n T: Copy,\n C: Index\n{\n let (x, y): (usize, usize) = (idx.x.try_into().unwrap(), idx.y.try_into().unwrap());\n &v[y][x]\n}\n"})}),"\n",(0,i.jsxs)(n.p,{children:["Given this, we can also give a more meaningful typename for indexing type, such\nas ",(0,i.jsx)(n.code,{children:"I"}),"."]}),"\n",(0,i.jsx)(n.h4,{id:"checking-bounds",children:"Checking bounds"}),"\n",(0,i.jsxs)(n.p,{children:["Now 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 ",(0,i.jsx)(n.code,{children:"Vector2D"})," to ",(0,i.jsx)(n.code,{children:"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",(0,i.jsx)(n.p,{children:"So how can we approach this then? Well\u2026 we will convert the bounds instead of\nthe indices and that lead us to:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"pub fn in_range(v: &[Vec], idx: &Vector2D) -> bool\nwhere\n usize: TryInto,\n >::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::::try_into(idx.y).unwrap()]\n .len()\n .try_into()\n .unwrap()\n}\n"})}),"\n",(0,i.jsxs)(n.p,{children:["You 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 ",(0,i.jsx)(n.code,{children:"usize"}),", ",(0,i.jsx)(n.strong,{children:"but"})," we also know that conversion like that\nreturns a ",(0,i.jsx)(n.code,{children:"Result"})," which we can use to our advantage."]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"pub fn in_range(v: &[Vec], idx: &Vector2D) -> bool\nwhere\n T: Copy,\n usize: TryFrom,\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",(0,i.jsxs)(n.p,{children:[(0,i.jsx)(n.code,{children:"Result"})," is a type similar to ",(0,i.jsx)(n.code,{children:"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",(0,i.jsxs)(n.p,{children:[(0,i.jsx)(n.code,{children:"try_from"})," is a method implemented in ",(0,i.jsx)(n.code,{children:"TryFrom"})," trait, that allows you to convert\ntypes and either successfully convert them or fail (with a reasonable error). This\nmethod returns ",(0,i.jsx)(n.code,{children:"Result"}),"."]}),"\n",(0,i.jsxs)(n.p,{children:["We call ",(0,i.jsx)(n.code,{children:"and_then"})," on that ",(0,i.jsx)(n.em,{children:"result"}),", let's have a look at the type signature of\n",(0,i.jsx)(n.code,{children:"and_then"}),", IMO it explains more than enough:"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"pub fn and_then(self, op: F) -> Result\nwhere\n F: FnOnce(T) -> Result\n"})}),"\n",(0,i.jsx)(n.p,{children:"OK\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",(0,i.jsxs)(n.blockquote,{children:["\n",(0,i.jsxs)(n.p,{children:[(0,i.jsx)(n.code,{children:"and_then"})," allows us to run an operation, which can fail, on the correct result"]}),"\n"]}),"\n",(0,i.jsxs)(n.p,{children:["We parsed a ",(0,i.jsx)(n.code,{children:"y"})," index and now we try to convert the ",(0,i.jsx)(n.code,{children:"x"})," index with ",(0,i.jsx)(n.code,{children:"try_from"}),"\nagain, but on that result we use ",(0,i.jsx)(n.code,{children:"map"})," rather than ",(0,i.jsx)(n.code,{children:"and_then"}),", why would that be?"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"pub fn map(self, op: F) -> Result\nwhere\n F: FnOnce(T) -> U\n"})}),"\n",(0,i.jsxs)(n.p,{children:["Huh\u2026 ",(0,i.jsx)(n.code,{children:"map"})," performs an operation that ",(0,i.jsx)(n.strong,{children:"cannot"})," fail. And finally we use\n",(0,i.jsx)(n.code,{children:"unwrap_or"})," which takes the value from result, or in case of an error returns the\ndefault that we define."]}),"\n",(0,i.jsxs)(n.p,{children:["How does this work then? If ",(0,i.jsx)(n.code,{children:"y"})," is negative, the conversion fails and the error\npropagates all the way to ",(0,i.jsx)(n.code,{children:"unwrap_or"}),", if ",(0,i.jsx)(n.code,{children:"y"})," can be a correct ",(0,i.jsx)(n.code,{children:"usize"})," value, then\nwe do the same with ",(0,i.jsx)(n.code,{children:"x"}),". If ",(0,i.jsx)(n.code,{children:"x"})," is negative, we propagate the error as with ",(0,i.jsx)(n.code,{children:"y"}),",\nand if it's not, then we check whether it exceeds the higher bounds or not."]}),"\n",(0,i.jsx)(n.h3,{id:"solution",children:"Solution"}),"\n",(0,i.jsx)(n.p,{children:"Relatively simple, you just need follow the rules and not get too smart, otherwise\nit will get back at you."}),"\n",(0,i.jsx)(n.h2,{id:"day-9-rope-bridge",children:(0,i.jsx)(n.a,{href:"https://adventofcode.com/2022/day/9",children:"Day 9: Rope Bridge"})}),"\n",(0,i.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(n.p,{children:"We get a rope with knots and we want to track how many different positions are\nvisited with the rope's tail."})}),"\n",(0,i.jsx)(n.p,{children:"By 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",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsx)(n.li,{children:"parsing"}),"\n",(0,i.jsx)(n.li,{children:"part 1 & 2"}),"\n",(0,i.jsx)(n.li,{children:"running on sample / input"}),"\n",(0,i.jsx)(n.li,{children:"tests"}),"\n"]}),"\n",(0,i.jsx)(n.p,{children:"Parsing 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",(0,i.jsxs)(n.p,{children:["Let's introduce and export a new module ",(0,i.jsx)(n.code,{children:"solution"})," that will take care of all of\nthis. We will start by introducing a trait for each day."]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"pub trait Solution {\n fn parse_input>(pathname: P) -> Input;\n\n fn part_1(input: &Input) -> Output;\n fn part_2(input: &Input) -> Output;\n}\n"})}),"\n",(0,i.jsxs)(n.p,{children:["This 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 ",(0,i.jsx)(n.code,{children:"Solution"})," trait."]}),"\n",(0,i.jsxs)(n.p,{children:["Now we need to get rid of the boilerplate, we can't get rid of the ",(0,i.jsx)(n.code,{children:"main"})," function,\nbut we can at least move out the functionality."]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:'fn 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",(0,i.jsxs)(n.p,{children:["This is all part of the ",(0,i.jsx)(n.code,{children:"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 ",(0,i.jsx)(n.code,{children:"Output"})," type to implement ",(0,i.jsx)(n.code,{children:"Display"})," that is necessary for the\n",(0,i.jsx)(n.code,{children:"info!"})," and format string there."]}),"\n",(0,i.jsxs)(n.p,{children:["Now we can get to first of the nasty things we are going to do\u2026 And it is the\n",(0,i.jsx)(n.code,{children:"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. ",(0,i.jsx)(n.code,{children:"day01"})," and we know that\nwe can ",(0,i.jsx)(n.em,{children:"somehow"})," deduce it from the structure name, given we name it reasonably."]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:'fn day() -> String {\n let mut day = String::from(type_name::().split("::").next().unwrap());\n day.make_ascii_lowercase();\n\n day.to_string()\n}\n'})}),"\n",(0,i.jsxs)(n.admonition,{type:"caution",children:[(0,i.jsx)(n.mdxAdmonitionTitle,{children:(0,i.jsx)(n.code,{children:"type_name"})}),(0,i.jsx)(n.p,{children:"This feature is still experimental and considered to be internal, it is not\nadvised to use it any production code."})]}),"\n",(0,i.jsxs)(n.p,{children:["And now we can get to the nastiest stuff ","\ud83d\ude29"," We will ",(0,i.jsx)(n.strong,{children:"generate"})," the tests!"]}),"\n",(0,i.jsx)(n.p,{children:"We want to be able to generate tests for sample input in a following way:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"test_sample!(day_01, Day01, 42, 69);\n"})}),"\n",(0,i.jsx)(n.p,{children:"There's not much we can do, so we will write a macro to generate the tests for us."}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:'#[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",(0,i.jsxs)(n.p,{children:["We 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 ",(0,i.jsx)(n.code,{children:"$"})," sign and you can define various \u201cforms\u201d\nof your macro. Let's go through it!"]}),"\n",(0,i.jsx)(n.p,{children:"We have following parameters:"}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"$mod_name"})," which represents the name for the module with tests, it is typed\nwith ",(0,i.jsx)(n.code,{children:"ident"})," which means that we want a valid identifier to be passed in."]}),"\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"$day_struct"})," represents the structure that will be used for tests, it is typed\nwith ",(0,i.jsx)(n.code,{children:"tt"})," which represents a ",(0,i.jsx)(n.em,{children:"token tree"}),", in our case it is a type."]}),"\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"$part_X"})," represents the expected output for the ",(0,i.jsx)(n.code,{children:"X"}),"th part and is of type ",(0,i.jsx)(n.code,{children:"expr"}),"\nwhich literally means an ",(0,i.jsx)(n.em,{children:"expression"}),"."]}),"\n"]}),"\n",(0,i.jsxs)(n.p,{children:["Apart from that we need to use ",(0,i.jsx)(n.code,{children:"#[macro_export]"})," to mark the macro as exported\nfor usage outside of the module. Now our skeleton looks like:"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:'use aoc_2022::*;\n\ntype Input = String;\ntype Output = String;\n\nstruct DayXX;\nimpl Solution for DayXX {\n fn parse_input>(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",(0,i.jsx)(n.h3,{id:"solution-1",children:"Solution"}),"\n",(0,i.jsx)(n.p,{children:"Not much to talk about, it is relatively easy to simulate."}),"\n",(0,i.jsx)(n.h2,{id:"day-10-cathode-ray-tube",children:(0,i.jsx)(n.a,{href:"https://adventofcode.com/2022/day/10",children:"Day 10: Cathode-Ray Tube"})}),"\n",(0,i.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(n.p,{children:"Emulating basic arithmetic operations on a CPU and drawing on CRT based on the\nCPU's accumulator."})}),"\n",(0,i.jsxs)(n.p,{children:["In this day I have discovered an issue with my design of the ",(0,i.jsx)(n.code,{children:"Solution"})," trait.\nAnd the issue is caused by different types of ",(0,i.jsx)(n.code,{children:"Output"})," for the part 1 and part 2."]}),"\n",(0,i.jsx)(n.p,{children:"Problem is relatively simple and consists of simulating a CPU, I have approached\nit in a following way:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"fn 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",(0,i.jsxs)(n.p,{children:["We just take the instructions, we have some state of the CPU and we execute the\ninstructions one-by-one. Perfect usage of the ",(0,i.jsx)(n.code,{children:"fold"})," (or ",(0,i.jsx)(n.code,{children:"reduce"})," as you may know\nit from other languages)."]}),"\n",(0,i.jsxs)(n.p,{children:["You can also see that we have an ",(0,i.jsx)(n.code,{children:"Output"})," type, so the question is how can we fix\nthat problem. And the answer is very simple and ",(0,i.jsx)(n.em,{children:"functional"}),". Rust allows you to\nhave an ",(0,i.jsx)(n.code,{children:"enumeration"})," that can ",(0,i.jsx)(n.em,{children:"bear"})," some other values apart from the type itself."]}),"\n",(0,i.jsxs)(n.admonition,{type:"tip",children:[(0,i.jsxs)(n.p,{children:["We could've seen something like this with the ",(0,i.jsx)(n.code,{children:"Result"})," type that can be\ndefined as"]}),(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"enum Result {\n Ok(T),\n Err(E)\n}\n"})}),(0,i.jsx)(n.h6,{id:"what-does-that-mean-though",children:"What does that mean though?"}),(0,i.jsxs)(n.p,{children:["When we have an ",(0,i.jsx)(n.code,{children:"Ok"})," value, it has the result itself, and when we get an ",(0,i.jsx)(n.code,{children:"Err"}),"\nvalue, it has the error. This also allows us to handle ",(0,i.jsx)(n.em,{children:"results"})," in a rather\npretty way:"]}),(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:'match do_something(x) {\n Ok(y) => {\n println!("SUCCESS: {}", y);\n },\n Err(y) => {\n eprintln!("ERROR: {}", y);\n }\n}\n'})})]}),"\n",(0,i.jsx)(n.p,{children:"My solution has a following outline:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"fn 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",(0,i.jsxs)(n.p,{children:["You might think that it's a perfectly reasonable thing to do. Yes, ",(0,i.jsx)(n.strong,{children:"but"})," notice\nthat the ",(0,i.jsx)(n.code,{children:"match"})," statement doesn't ",(0,i.jsx)(n.em,{children:"collect"})," the changes in any way and also we\npass ",(0,i.jsx)(n.code,{children:"output"})," by ",(0,i.jsx)(n.code,{children:"&mut"}),", so it is shared across each ",(0,i.jsx)(n.em,{children:"iteration"})," of the ",(0,i.jsx)(n.code,{children:"fold"}),"."]}),"\n",(0,i.jsxs)(n.p,{children:["The dirty and ingenious thing is that ",(0,i.jsx)(n.code,{children:"x"}),"s are passed by ",(0,i.jsx)(n.code,{children:"&mut"})," too and therefore\nthey are directly modified by the helper functions. To sum it up and let it sit"]}),"\n",(0,i.jsxs)(n.blockquote,{children:["\n",(0,i.jsxs)(n.p,{children:["We are ",(0,i.jsx)(n.strong,{children:"collecting"})," the result ",(0,i.jsx)(n.strong,{children:"into"})," an ",(0,i.jsx)(n.strong,{children:"enumeration"})," that is ",(0,i.jsx)(n.strong,{children:"shared"}),"\nacross ",(0,i.jsx)(n.strong,{children:"all"})," iterations of ",(0,i.jsx)(n.code,{children:"fold"}),"."]}),"\n"]}),"\n",(0,i.jsx)(n.h3,{id:"solution-2",children:"Solution"}),"\n",(0,i.jsxs)(n.p,{children:["Similar to ",(0,i.jsx)(n.em,{children:"Day 9"}),", but there are some technical details that can get you."]}),"\n",(0,i.jsx)(n.h2,{id:"day-11-monkey-in-the-middle",children:(0,i.jsx)(n.a,{href:"https://adventofcode.com/2022/day/11",children:"Day 11: Monkey in the Middle"})}),"\n",(0,i.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(n.p,{children:"Simulation of monkeys throwing stuff around and measuring your stress levels\nwhile your stuff is being passed around."})}),"\n",(0,i.jsx)(n.p,{children:"I think I decided to use regular expressions here for the first time, cause\nparsing the input was a pain."}),"\n",(0,i.jsx)(n.p,{children:"Also I didn't expect to implement Euclidean algorithm in Rust\u2026"}),"\n",(0,i.jsx)(n.h3,{id:"solution-3",children:"Solution"}),"\n",(0,i.jsx)(n.p,{children:"Again, 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",(0,i.jsx)(n.h2,{id:"day-12-hill-climbing-algorithm",children:(0,i.jsx)(n.a,{href:"https://adventofcode.com/2022/day/12",children:"Day 12: Hill Climbing Algorithm"})}),"\n",(0,i.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(n.p,{children:"Finding shortest path up the hill and also shortest path down to the ground while\nalso rolling down the hill\u2026"})}),"\n",(0,i.jsxs)(n.p,{children:["As I have said in the ",(0,i.jsx)(n.em,{children:"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",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"fn bfs(\n graph: &[Vec], start: &Position, has_edge: F, is_target: G\n) -> Option\nwhere\n F: Fn(&[Vec], &Position, &Position) -> bool,\n G: Fn(&[Vec], &Position) -> bool\n"})}),"\n",(0,i.jsxs)(n.p,{children:["We pass the initial vertex from the caller and everything else is left to the BFS\nalgorithm, based on the ",(0,i.jsx)(n.code,{children:"has_edge"})," and ",(0,i.jsx)(n.code,{children:"is_target"})," functions."]}),"\n",(0,i.jsxs)(n.p,{children:["This was easy! And that is not very usual in Rust once you want to pass around\nfunctions. ","\ud83d\udc40"]}),"\n",(0,i.jsx)(n.h3,{id:"solution-4",children:"Solution"}),"\n",(0,i.jsxs)(n.p,{children:["Looking for the shortest path\u2026 Must be Dijkstra, right? ",(0,i.jsx)(n.strong,{children:"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, ",(0,i.jsx)(n.strong,{children:"but"})," if you know that\nall connected vertices are in a unit (actually ",(0,i.jsxs)(n.span,{className:"katex",children:[(0,i.jsx)(n.span,{className:"katex-mathml",children:(0,i.jsx)(n.math,{xmlns:"http://www.w3.org/1998/Math/MathML",children:(0,i.jsxs)(n.semantics,{children:[(0,i.jsxs)(n.mrow,{children:[(0,i.jsx)(n.mi,{children:"d"}),(0,i.jsx)(n.mo,{children:"="}),(0,i.jsx)(n.mn,{children:"1"})]}),(0,i.jsx)(n.annotation,{encoding:"application/x-tex",children:"d = 1"})]})})}),(0,i.jsxs)(n.span,{className:"katex-html","aria-hidden":"true",children:[(0,i.jsxs)(n.span,{className:"base",children:[(0,i.jsx)(n.span,{className:"strut",style:{height:"0.6944em"}}),(0,i.jsx)(n.span,{className:"mord mathnormal",children:"d"}),(0,i.jsx)(n.span,{className:"mspace",style:{marginRight:"0.2778em"}}),(0,i.jsx)(n.span,{className:"mrel",children:"="}),(0,i.jsx)(n.span,{className:"mspace",style:{marginRight:"0.2778em"}})]}),(0,i.jsxs)(n.span,{className:"base",children:[(0,i.jsx)(n.span,{className:"strut",style:{height:"0.6444em"}}),(0,i.jsx)(n.span,{className:"mord",children:"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",(0,i.jsx)(n.h2,{id:"day-13-distress-signal",children:(0,i.jsx)(n.a,{href:"https://adventofcode.com/2022/day/13",children:"Day 13: Distress Signal"})}),"\n",(0,i.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(n.p,{children:"Processing packets with structured data from the distress signal."})}),"\n",(0,i.jsxs)(n.p,{children:["You can implement a lot of traits if you want to. It is ",(0,i.jsx)(n.em,{children:"imperative"})," to implement\nordering on the packets. I had a typo, so I also proceeded to implement a ",(0,i.jsx)(n.code,{children:"Display"}),"\ntrait for debugging purposes:"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:'impl 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",(0,i.jsx)(n.h3,{id:"solution-5",children:"Solution"}),"\n",(0,i.jsx)(n.p,{children:"A lot of technical details\u2026 Parsing is nasty too\u2026"}),"\n",(0,i.jsx)(n.h2,{id:"day-14-regolith-reservoir",children:(0,i.jsx)(n.a,{href:"https://adventofcode.com/2022/day/14",children:"Day 14: Regolith Reservoir"})}),"\n",(0,i.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(n.p,{children:"Let's simulate falling sand grain-by-grain."})}),"\n",(0,i.jsxs)(n.p,{children:["Again, both parts are relatively similar with minimal changes, so it is a good\nidea to refactor it a bit. Similar approach to the ",(0,i.jsx)(n.a,{href:"#day-12-hill-climbing-algorithm",children:"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",(0,i.jsx)(n.h3,{id:"solution-6",children:"Solution"}),"\n",(0,i.jsx)(n.p,{children:"Tedious."}),"\n",(0,i.jsx)(n.h2,{id:"post-mortem",children:"Post Mortem"}),"\n",(0,i.jsx)(n.h3,{id:"indexing",children:"Indexing"}),"\n",(0,i.jsxs)(n.p,{children:["I was asked about the indexing after publishing the blog. And truly it is rather\ncomplicated topic, especially after releasing ",(0,i.jsx)(n.code,{children:"SliceIndex"})," trait. I couldn't\nleave it be, so I tried to implement the ",(0,i.jsx)(n.code,{children:"Index"})," and ",(0,i.jsx)(n.code,{children:"IndexMut"})," trait."]}),"\n",(0,i.jsx)(n.admonition,{type:"note",children:(0,i.jsxs)(n.p,{children:["I have also mentioned that the ",(0,i.jsx)(n.code,{children:"SliceIndex"})," trait is ",(0,i.jsx)(n.code,{children:"unsafe"}),", but truth be told,\nonly ",(0,i.jsx)(n.em,{children:"unsafe"})," part are the 2 methods that are named ",(0,i.jsx)(n.code,{children:"*unchecked*"}),". Anyways, I will\nbe implementing the ",(0,i.jsx)(n.code,{children:"Index*"})," traits for now, rather than the ",(0,i.jsx)(n.code,{children:"SliceIndex"}),"."]})}),"\n",(0,i.jsx)(n.p,{children:"It's relatively straightforward\u2026"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"impl Index> for [C]\nwhere\n I: Copy + TryInto,\n >::Error: Debug,\n C: Index,\n{\n type Output = C::Output;\n\n fn index(&self, index: Vector2D) -> &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 IndexMut> for [C]\nwhere\n I: Copy + TryInto,\n >::Error: Debug,\n C: IndexMut,\n{\n fn index_mut(&mut self, index: Vector2D) -> &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",(0,i.jsxs)(n.p,{children:["We can see a lot of similarities to the implementation of ",(0,i.jsx)(n.code,{children:"index"})," and ",(0,i.jsx)(n.code,{children:"index_mut"}),"\nfunctions. In the end, they are 1:1, just wrapped in the trait that provides a\nsyntax sugar for ",(0,i.jsx)(n.code,{children:"container[idx]"}),"."]}),"\n",(0,i.jsxs)(n.admonition,{type:"note",children:[(0,i.jsxs)(n.p,{children:["I have also switched from using the ",(0,i.jsx)(n.code,{children:"TryFrom"})," to ",(0,i.jsx)(n.code,{children:"TryInto"})," trait, since it better\nmatches what we are using, the ",(0,i.jsx)(n.code,{children:".try_into"})," rather than ",(0,i.jsx)(n.code,{children:"usize::try_from"}),"."]}),(0,i.jsxs)(n.p,{children:["Also implementing ",(0,i.jsx)(n.code,{children:"TryFrom"})," automatically provides you with a ",(0,i.jsx)(n.code,{children:"TryInto"})," trait,\nsince it is relatively easy to implement. Just compare the following:"]}),(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"pub trait TryFrom: Sized {\n type Error;\n\n fn try_from(value: T) -> Result;\n}\n\npub trait TryInto: Sized {\n type Error;\n\n fn try_into(self) -> Result;\n}\n"})})]}),"\n",(0,i.jsxs)(n.p,{children:["OK, so we have our trait implemented, we should be able to use ",(0,i.jsx)(n.code,{children:"container[index]"}),",\nright? Yes\u2026 but actually no ","\ud83d\ude26"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{children:"error[E0277]: the type `[std::vec::Vec]` cannot be indexed by `aoc_2022::Vector2D`\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]>` is not implemented for `aoc_2022::Vector2D`\n = note: required for `std::vec::Vec>` to implement `std::ops::Index>`\n\nerror[E0277]: the type `[std::vec::Vec]` cannot be indexed by `aoc_2022::Vector2D`\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]>` is not implemented for `aoc_2022::Vector2D`\n = note: required for `std::vec::Vec>` to implement `std::ops::Index>`\n\nerror[E0277]: the type `[std::vec::Vec]` cannot be indexed by `aoc_2022::Vector2D`\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]>` is not implemented for `aoc_2022::Vector2D`\n = note: required for `std::vec::Vec>` to implement `std::ops::Index>`\n"})}),"\n",(0,i.jsxs)(n.p,{children:["Why? We have it implemented for the slices (",(0,i.jsx)(n.code,{children:"[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 ",(0,i.jsx)(n.code,{children:"&[Vec]"}),", but this is coming from a helper functions that\ntake ",(0,i.jsx)(n.code,{children:"&Vec>"})," instead. And\u2026 we don't implement ",(0,i.jsx)(n.code,{children:"Index"})," and ",(0,i.jsx)(n.code,{children:"IndexMut"})," for\nthose. Just for the slices. ","\ud83e\udd2f"," ",(0,i.jsx)(n.em,{children:"What are we going to do about it?"})]}),"\n",(0,i.jsxs)(n.p,{children:["We 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 ",(0,i.jsx)(n.strong,{children:"at all"}),"!"]}),"\n",(0,i.jsx)(n.p,{children:"Implementing the macro can be done in a following way:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"macro_rules! generate_indices {\n ($container:ty) => {\n impl Index> for $container\n where\n I: Copy + TryInto,\n >::Error: Debug,\n C: Index,\n {\n type Output = C::Output;\n\n fn index(&self, index: Vector2D) -> &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 IndexMut> for $container\n where\n I: Copy + TryInto,\n >::Error: Debug,\n C: IndexMut,\n {\n fn index_mut(&mut self, index: Vector2D) -> &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",(0,i.jsx)(n.p,{children:"And now we can simply do"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"generate_indices!(VecDeque);\ngenerate_indices!([C]);\ngenerate_indices!(Vec);\n// generate_indices!([C; N], const N: usize);\n"})}),"\n",(0,i.jsxs)(n.p,{children:["The last type (I took the inspiration from the implementations of the ",(0,i.jsx)(n.code,{children:"Index"})," and\n",(0,i.jsx)(n.code,{children:"IndexMut"})," traits) is a bit problematic, because of the ",(0,i.jsx)(n.code,{children:"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",(0,i.jsx)(n.admonition,{type:"note",children:(0,i.jsxs)(n.p,{children:["If I were to use 2D-indexing over ",(0,i.jsx)(n.code,{children:"[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",(0,i.jsx)(n.h4,{id:"cause-of-the-problem",children:"Cause of the problem"}),"\n",(0,i.jsxs)(n.p,{children:["This issue is relatively funny. If you don't use any type aliases, just the raw\ntypes, you'll get suggested certain changes by the ",(0,i.jsx)(n.em,{children:"clippy"}),". For example if you\nconsider the following piece of code"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:'fn get_sum(nums: &Vec) -> 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",(0,i.jsxs)(n.p,{children:["and you run ",(0,i.jsx)(n.em,{children:"clippy"})," on it, you will get"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{children:'Checking 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 {\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",(0,i.jsx)(n.p,{children:"However, if you introduce a type alias, such as"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"type Numbers = Vec;\n"})}),"\n",(0,i.jsxs)(n.p,{children:["Then ",(0,i.jsx)(n.em,{children:"clippy"})," won't say anything, cause there is literally nothing to suggest.\nHowever the outcome is not the same\u2026"]})]})}function h(e={}){const{wrapper:n}={...(0,s.a)(),...e.components};return n?(0,i.jsx)(n,{...e,children:(0,i.jsx)(c,{...e})}):c(e)}},11151:(e,n,t)=>{t.d(n,{Z:()=>a,a:()=>o});var i=t(67294);const s={},r=i.createContext(s);function o(e){const n=i.useContext(r);return i.useMemo((function(){return"function"==typeof e?e(n):{...n,...e}}),[n,e])}function a(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(s):e.components||s:o(e.components),i.createElement(r.Provider,{value:n},e.children)}}}]); \ No newline at end of file +"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[1011],{7582:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>d,contentTitle:()=>o,default:()=>h,frontMatter:()=>r,metadata:()=>a,toc:()=>l});var i=t(85893),s=t(11151);const r={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:!1},o=void 0,a={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:!0,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:!1},unlisted:!1,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"}},d={authorsImageUrls:[void 0]},l=[{value:"Day 8: Treetop Tree House",id:"day-8-treetop-tree-house",level:2},{value:"Swapping indices",id:"swapping-indices",level:4},{value:"Indexing Vec",id:"indexing-vec",level:4},{value:"Issues",id:"issues",level:5},{value:"Checking bounds",id:"checking-bounds",level:4},{value:"Solution",id:"solution",level:3},{value:"Day 9: Rope Bridge",id:"day-9-rope-bridge",level:2},{value:"Solution",id:"solution-1",level:3},{value:"Day 10: Cathode-Ray Tube",id:"day-10-cathode-ray-tube",level:2},{value:"What does that mean though?",id:"what-does-that-mean-though",level:6},{value:"Solution",id:"solution-2",level:3},{value:"Day 11: Monkey in the Middle",id:"day-11-monkey-in-the-middle",level:2},{value:"Solution",id:"solution-3",level:3},{value:"Day 12: Hill Climbing Algorithm",id:"day-12-hill-climbing-algorithm",level:2},{value:"Solution",id:"solution-4",level:3},{value:"Day 13: Distress Signal",id:"day-13-distress-signal",level:2},{value:"Solution",id:"solution-5",level:3},{value:"Day 14: Regolith Reservoir",id:"day-14-regolith-reservoir",level:2},{value:"Solution",id:"solution-6",level:3},{value:"Post Mortem",id:"post-mortem",level:2},{value:"Indexing",id:"indexing",level:3},{value:"Cause of the problem",id:"cause-of-the-problem",level:4}];function c(e){const n={a:"a",admonition:"admonition",annotation:"annotation",blockquote:"blockquote",code:"code",em:"em",h2:"h2",h3:"h3",h4:"h4",h5:"h5",h6:"h6",li:"li",math:"math",mdxAdmonitionTitle:"mdxAdmonitionTitle",mi:"mi",mn:"mn",mo:"mo",mrow:"mrow",p:"p",pre:"pre",semantics:"semantics",span:"span",strong:"strong",ul:"ul",...(0,s.a)(),...e.components};return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)(n.p,{children:["Let's go through the second week of ",(0,i.jsx)(n.a,{href:"https://adventofcode.com",children:(0,i.jsx)(n.em,{children:"Advent of Code"})})," in Rust."]}),"\n",(0,i.jsx)(n.h2,{id:"day-8-treetop-tree-house",children:(0,i.jsx)(n.a,{href:"https://adventofcode.com/2022/day/8",children:"Day 8: Treetop Tree House"})}),"\n",(0,i.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(n.p,{children:"We 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",(0,i.jsxs)(n.p,{children:["Nothing 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 ",(0,i.jsx)(n.code,{children:"Vector2D"})," and now it's time to extend it with indexing\nof ",(0,i.jsx)(n.code,{children:"Vec"})," of ",(0,i.jsx)(n.code,{children:"Vec"}),"s. In my solution I was manipulating with indices in the following\nway:"]}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsx)(n.li,{children:"swapping them"}),"\n",(0,i.jsxs)(n.li,{children:["checking whether they are correct indices for the ",(0,i.jsx)(n.code,{children:"Vec>"})]}),"\n",(0,i.jsxs)(n.li,{children:["indexing ",(0,i.jsx)(n.code,{children:"Vec>"})," with them"]}),"\n"]}),"\n",(0,i.jsx)(n.admonition,{type:"caution",children:(0,i.jsxs)(n.p,{children:["I'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 ",(0,i.jsx)(n.em,{children:"thicc"})," ",(0,i.jsx)(n.strong,{children:"\xab\u21af\xbb"})," mark and will try to \u201clock\u201d them into their\nown \u201cbox of hell\u201d."]})}),"\n",(0,i.jsx)(n.h4,{id:"swapping-indices",children:"Swapping indices"}),"\n",(0,i.jsx)(n.p,{children:"Relatively simple implementation, just take the values, swap them and return new\nvector."}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"impl Vector2D {\n pub fn swap(&self) -> Self {\n Self {\n x: self.y,\n y: self.x,\n }\n }\n}\n"})}),"\n",(0,i.jsxs)(n.p,{children:["Pretty straight-forward implementation, but let's talk about the ",(0,i.jsx)(n.code,{children:"T: Copy"}),". We\nneed to use it, since we are returning a ",(0,i.jsx)(n.strong,{children:"new"})," vector, with swapped ",(0,i.jsx)(n.strong,{children:"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",(0,i.jsxs)(n.h4,{id:"indexing-vec",children:["Indexing ",(0,i.jsx)(n.code,{children:"Vec"})]}),"\n",(0,i.jsx)(n.p,{children:"I will start with the indexing, cause bound-checking is a bit more\u2026 complicated\nthan I would like to."}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"pub fn index<'a, T, U>(v: &'a [Vec], idx: &Vector2D) -> &'a U\nwhere\n usize: TryFrom,\n >::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",(0,i.jsxs)(n.p,{children:["Let'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 ",(0,i.jsx)(n.code,{children:"x"})," and ",(0,i.jsx)(n.code,{children:"y"})," and convert\nthem both to ",(0,i.jsx)(n.code,{children:"usize"})," type that can be used later on for indexing."]}),"\n",(0,i.jsxs)(n.p,{children:["The type signature of the function is where the fun is at ","\ud83d\ude09"," We are trying\nto convert unknown type to ",(0,i.jsx)(n.code,{children:"usize"}),", so we must bound the ",(0,i.jsx)(n.code,{children:"T"})," as a type that can\nbe converted to ",(0,i.jsx)(n.code,{children:"usize"}),", that's how we got ",(0,i.jsx)(n.code,{children:"usize: TryFrom"})," which basically\nsays that ",(0,i.jsx)(n.code,{children:"usize"})," must implement ",(0,i.jsx)(n.code,{children:"TryFrom"})," trait and therefore allows us to\nconvert the indices to actual ",(0,i.jsx)(n.code,{children:"usize"})," indices. Using ",(0,i.jsx)(n.code,{children:".unwrap()"})," also forces us\nto bound the error that can occur when converting ",(0,i.jsx)(n.code,{children:"T"})," into ",(0,i.jsx)(n.code,{children:"usize"}),", that's how\nwe get ",(0,i.jsx)(n.code,{children:">::Error: Debug"})," which loosely means"]}),"\n",(0,i.jsxs)(n.blockquote,{children:["\n",(0,i.jsxs)(n.p,{children:["error during conversion of ",(0,i.jsx)(n.code,{children:"T"})," into ",(0,i.jsx)(n.code,{children:"usize"})," must implement ",(0,i.jsx)(n.code,{children:"Debug"}),",\ni.e. can be printed in some way or other"]}),"\n"]}),"\n",(0,i.jsxs)(n.p,{children:[(0,i.jsx)(n.code,{children:"T: Copy"})," is required by ",(0,i.jsx)(n.code,{children:".try_into()"})," which takes ",(0,i.jsx)(n.code,{children:"T"})," by-value."]}),"\n",(0,i.jsx)(n.p,{children:"And now we are left only with the first line of the definition."}),"\n",(0,i.jsx)(n.admonition,{type:"note",children:(0,i.jsx)(n.p,{children:"Skilled 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",(0,i.jsx)(n.p,{children:"Let's split it in multiple parts:"}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"v: &'a [Vec]"})," represents the 2D ",(0,i.jsx)(n.code,{children:"Vec"}),", we are indexing, ",(0,i.jsx)(n.code,{children:"Vec"})," implements\n",(0,i.jsx)(n.code,{children:"Slice"})," trait and ",(0,i.jsx)(n.em,{children:"clippy"})," recommends using ",(0,i.jsx)(n.code,{children:"&[T]"})," to ",(0,i.jsx)(n.code,{children:"&Vec"}),", exact details\nare unknown to me"]}),"\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"idx: &Vector2D"})," represents the ",(0,i.jsx)(n.em,{children:"indices"})," which we use, we take them by\nreference to avoid an unnecessary copy"]}),"\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"-> &'a U"})," means that we are returning a ",(0,i.jsx)(n.em,{children:"reference"})," to some value of type ",(0,i.jsx)(n.code,{children:"U"}),".\nNow the question is what does the ",(0,i.jsx)(n.code,{children:"'a"})," mean, we can also see it as a generic\ntype declared along ",(0,i.jsx)(n.code,{children:"T"})," and ",(0,i.jsx)(n.code,{children:"U"}),". And the answer is ",(0,i.jsx)(n.em,{children:"relatively"})," simple, ",(0,i.jsx)(n.code,{children:"'a"}),"\nrepresents a ",(0,i.jsx)(n.em,{children:"lifetime"}),". We take the ",(0,i.jsx)(n.code,{children:"v"})," by a reference and return a reference,\nborrow checker validates all of the ",(0,i.jsx)(n.em,{children:"borrows"})," (or references), so we need to\nspecify that our returned value has ",(0,i.jsx)(n.em,{children:"the same lifetime"})," as the vector we have\ntaken by a reference, i.e. returned reference must live at least as long as the\n",(0,i.jsx)(n.code,{children:"v"}),". This way we can \u201cbe sure\u201d that the returned reference is valid."]}),"\n"]}),"\n",(0,i.jsx)(n.h5,{id:"issues",children:"Issues"}),"\n",(0,i.jsxs)(n.p,{children:["First 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. ",(0,i.jsx)(n.code,{children:"index_mut"}),". Which I have actually done while writing this part:"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"pub fn index_mut<'a, T, U>(v: &'a mut [Vec], idx: &Vector2D) -> &'a mut U\nwhere\n usize: TryFrom,\n >::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",(0,i.jsxs)(n.admonition,{type:"caution",children:[(0,i.jsxs)(n.mdxAdmonitionTitle,{children:[(0,i.jsx)(n.strong,{children:"\xab\u21af\xbb"})," Why can't we use one function?"]}),(0,i.jsxs)(n.p,{children:["When we consider a ",(0,i.jsx)(n.code,{children:"Vec"}),", we don't need to consider containers as ",(0,i.jsx)(n.code,{children:"T"}),", Rust\nimplements indexing as traits ",(0,i.jsx)(n.code,{children:"Index"})," and ",(0,i.jsx)(n.code,{children:"IndexMut"})," that do the dirty work\nbehind syntactic sugar of ",(0,i.jsx)(n.code,{children:"container[idx]"}),"."]}),(0,i.jsxs)(n.p,{children:["However, implementing of traits is not allowed for ",(0,i.jsx)(n.em,{children:"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."]}),(0,i.jsxs)(n.p,{children:["Another part of this rabbit hole is trait ",(0,i.jsx)(n.code,{children:"SliceIndex"})," that is of a relevance\nbecause of"]}),(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"impl Index for [T]\nwhere\n I: SliceIndex<[T]>\n\nimpl Index for Vec\nwhere\n I: SliceIndex<[T]>,\n A: Allocator\n\nimpl Index for [T; N]\nwhere\n [T]: Index\n"})}),(0,i.jsxs)(n.p,{children:["In other words, if your type implements ",(0,i.jsx)(n.code,{children:"SliceIndex"})," trait, it can be used\nfor indexing. As of now, this trait has all of its required methods experimental\nand is marked as ",(0,i.jsx)(n.code,{children:"unsafe"}),"."]})]}),"\n",(0,i.jsxs)(n.p,{children:["Another problem is a requirement for indexing either ",(0,i.jsx)(n.code,{children:"[Vec]"})," or ",(0,i.jsx)(n.code,{children:"Vec>"}),".\nThis requirement could be countered by removing inner type ",(0,i.jsx)(n.code,{children:"Vec"})," and constraining\nit by a trait ",(0,i.jsx)(n.code,{children:"Index"})," (or ",(0,i.jsx)(n.code,{children:"IndexMut"})," respectively) in a following way"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"pub fn index<'a, C, T>(v: &'a [C], idx: &Vector2D) -> &'a C::Output\nwhere\n usize: TryFrom,\n >::Error: Debug,\n T: Copy,\n C: Index\n{\n let (x, y): (usize, usize) = (idx.x.try_into().unwrap(), idx.y.try_into().unwrap());\n &v[y][x]\n}\n"})}),"\n",(0,i.jsxs)(n.p,{children:["Given this, we can also give a more meaningful typename for indexing type, such\nas ",(0,i.jsx)(n.code,{children:"I"}),"."]}),"\n",(0,i.jsx)(n.h4,{id:"checking-bounds",children:"Checking bounds"}),"\n",(0,i.jsxs)(n.p,{children:["Now 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 ",(0,i.jsx)(n.code,{children:"Vector2D"})," to ",(0,i.jsx)(n.code,{children:"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",(0,i.jsx)(n.p,{children:"So how can we approach this then? Well\u2026 we will convert the bounds instead of\nthe indices and that lead us to:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"pub fn in_range(v: &[Vec], idx: &Vector2D) -> bool\nwhere\n usize: TryInto,\n >::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::::try_into(idx.y).unwrap()]\n .len()\n .try_into()\n .unwrap()\n}\n"})}),"\n",(0,i.jsxs)(n.p,{children:["You 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 ",(0,i.jsx)(n.code,{children:"usize"}),", ",(0,i.jsx)(n.strong,{children:"but"})," we also know that conversion like that\nreturns a ",(0,i.jsx)(n.code,{children:"Result"})," which we can use to our advantage."]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"pub fn in_range(v: &[Vec], idx: &Vector2D) -> bool\nwhere\n T: Copy,\n usize: TryFrom,\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",(0,i.jsxs)(n.p,{children:[(0,i.jsx)(n.code,{children:"Result"})," is a type similar to ",(0,i.jsx)(n.code,{children:"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",(0,i.jsxs)(n.p,{children:[(0,i.jsx)(n.code,{children:"try_from"})," is a method implemented in ",(0,i.jsx)(n.code,{children:"TryFrom"})," trait, that allows you to convert\ntypes and either successfully convert them or fail (with a reasonable error). This\nmethod returns ",(0,i.jsx)(n.code,{children:"Result"}),"."]}),"\n",(0,i.jsxs)(n.p,{children:["We call ",(0,i.jsx)(n.code,{children:"and_then"})," on that ",(0,i.jsx)(n.em,{children:"result"}),", let's have a look at the type signature of\n",(0,i.jsx)(n.code,{children:"and_then"}),", IMO it explains more than enough:"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"pub fn and_then(self, op: F) -> Result\nwhere\n F: FnOnce(T) -> Result\n"})}),"\n",(0,i.jsx)(n.p,{children:"OK\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",(0,i.jsxs)(n.blockquote,{children:["\n",(0,i.jsxs)(n.p,{children:[(0,i.jsx)(n.code,{children:"and_then"})," allows us to run an operation, which can fail, on the correct result"]}),"\n"]}),"\n",(0,i.jsxs)(n.p,{children:["We parsed a ",(0,i.jsx)(n.code,{children:"y"})," index and now we try to convert the ",(0,i.jsx)(n.code,{children:"x"})," index with ",(0,i.jsx)(n.code,{children:"try_from"}),"\nagain, but on that result we use ",(0,i.jsx)(n.code,{children:"map"})," rather than ",(0,i.jsx)(n.code,{children:"and_then"}),", why would that be?"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"pub fn map(self, op: F) -> Result\nwhere\n F: FnOnce(T) -> U\n"})}),"\n",(0,i.jsxs)(n.p,{children:["Huh\u2026 ",(0,i.jsx)(n.code,{children:"map"})," performs an operation that ",(0,i.jsx)(n.strong,{children:"cannot"})," fail. And finally we use\n",(0,i.jsx)(n.code,{children:"unwrap_or"})," which takes the value from result, or in case of an error returns the\ndefault that we define."]}),"\n",(0,i.jsxs)(n.p,{children:["How does this work then? If ",(0,i.jsx)(n.code,{children:"y"})," is negative, the conversion fails and the error\npropagates all the way to ",(0,i.jsx)(n.code,{children:"unwrap_or"}),", if ",(0,i.jsx)(n.code,{children:"y"})," can be a correct ",(0,i.jsx)(n.code,{children:"usize"})," value, then\nwe do the same with ",(0,i.jsx)(n.code,{children:"x"}),". If ",(0,i.jsx)(n.code,{children:"x"})," is negative, we propagate the error as with ",(0,i.jsx)(n.code,{children:"y"}),",\nand if it's not, then we check whether it exceeds the higher bounds or not."]}),"\n",(0,i.jsx)(n.h3,{id:"solution",children:"Solution"}),"\n",(0,i.jsx)(n.p,{children:"Relatively simple, you just need follow the rules and not get too smart, otherwise\nit will get back at you."}),"\n",(0,i.jsx)(n.h2,{id:"day-9-rope-bridge",children:(0,i.jsx)(n.a,{href:"https://adventofcode.com/2022/day/9",children:"Day 9: Rope Bridge"})}),"\n",(0,i.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(n.p,{children:"We get a rope with knots and we want to track how many different positions are\nvisited with the rope's tail."})}),"\n",(0,i.jsx)(n.p,{children:"By 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",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsx)(n.li,{children:"parsing"}),"\n",(0,i.jsx)(n.li,{children:"part 1 & 2"}),"\n",(0,i.jsx)(n.li,{children:"running on sample / input"}),"\n",(0,i.jsx)(n.li,{children:"tests"}),"\n"]}),"\n",(0,i.jsx)(n.p,{children:"Parsing 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",(0,i.jsxs)(n.p,{children:["Let's introduce and export a new module ",(0,i.jsx)(n.code,{children:"solution"})," that will take care of all of\nthis. We will start by introducing a trait for each day."]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"pub trait Solution {\n fn parse_input>(pathname: P) -> Input;\n\n fn part_1(input: &Input) -> Output;\n fn part_2(input: &Input) -> Output;\n}\n"})}),"\n",(0,i.jsxs)(n.p,{children:["This 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 ",(0,i.jsx)(n.code,{children:"Solution"})," trait."]}),"\n",(0,i.jsxs)(n.p,{children:["Now we need to get rid of the boilerplate, we can't get rid of the ",(0,i.jsx)(n.code,{children:"main"})," function,\nbut we can at least move out the functionality."]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:'fn 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",(0,i.jsxs)(n.p,{children:["This is all part of the ",(0,i.jsx)(n.code,{children:"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 ",(0,i.jsx)(n.code,{children:"Output"})," type to implement ",(0,i.jsx)(n.code,{children:"Display"})," that is necessary for the\n",(0,i.jsx)(n.code,{children:"info!"})," and format string there."]}),"\n",(0,i.jsxs)(n.p,{children:["Now we can get to first of the nasty things we are going to do\u2026 And it is the\n",(0,i.jsx)(n.code,{children:"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. ",(0,i.jsx)(n.code,{children:"day01"})," and we know that\nwe can ",(0,i.jsx)(n.em,{children:"somehow"})," deduce it from the structure name, given we name it reasonably."]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:'fn day() -> String {\n let mut day = String::from(type_name::().split("::").next().unwrap());\n day.make_ascii_lowercase();\n\n day.to_string()\n}\n'})}),"\n",(0,i.jsxs)(n.admonition,{type:"caution",children:[(0,i.jsx)(n.mdxAdmonitionTitle,{children:(0,i.jsx)(n.code,{children:"type_name"})}),(0,i.jsx)(n.p,{children:"This feature is still experimental and considered to be internal, it is not\nadvised to use it any production code."})]}),"\n",(0,i.jsxs)(n.p,{children:["And now we can get to the nastiest stuff ","\ud83d\ude29"," We will ",(0,i.jsx)(n.strong,{children:"generate"})," the tests!"]}),"\n",(0,i.jsx)(n.p,{children:"We want to be able to generate tests for sample input in a following way:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"test_sample!(day_01, Day01, 42, 69);\n"})}),"\n",(0,i.jsx)(n.p,{children:"There's not much we can do, so we will write a macro to generate the tests for us."}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:'#[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",(0,i.jsxs)(n.p,{children:["We 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 ",(0,i.jsx)(n.code,{children:"$"})," sign and you can define various \u201cforms\u201d\nof your macro. Let's go through it!"]}),"\n",(0,i.jsx)(n.p,{children:"We have following parameters:"}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"$mod_name"})," which represents the name for the module with tests, it is typed\nwith ",(0,i.jsx)(n.code,{children:"ident"})," which means that we want a valid identifier to be passed in."]}),"\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"$day_struct"})," represents the structure that will be used for tests, it is typed\nwith ",(0,i.jsx)(n.code,{children:"tt"})," which represents a ",(0,i.jsx)(n.em,{children:"token tree"}),", in our case it is a type."]}),"\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"$part_X"})," represents the expected output for the ",(0,i.jsx)(n.code,{children:"X"}),"th part and is of type ",(0,i.jsx)(n.code,{children:"expr"}),"\nwhich literally means an ",(0,i.jsx)(n.em,{children:"expression"}),"."]}),"\n"]}),"\n",(0,i.jsxs)(n.p,{children:["Apart from that we need to use ",(0,i.jsx)(n.code,{children:"#[macro_export]"})," to mark the macro as exported\nfor usage outside of the module. Now our skeleton looks like:"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:'use aoc_2022::*;\n\ntype Input = String;\ntype Output = String;\n\nstruct DayXX;\nimpl Solution for DayXX {\n fn parse_input>(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",(0,i.jsx)(n.h3,{id:"solution-1",children:"Solution"}),"\n",(0,i.jsx)(n.p,{children:"Not much to talk about, it is relatively easy to simulate."}),"\n",(0,i.jsx)(n.h2,{id:"day-10-cathode-ray-tube",children:(0,i.jsx)(n.a,{href:"https://adventofcode.com/2022/day/10",children:"Day 10: Cathode-Ray Tube"})}),"\n",(0,i.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(n.p,{children:"Emulating basic arithmetic operations on a CPU and drawing on CRT based on the\nCPU's accumulator."})}),"\n",(0,i.jsxs)(n.p,{children:["In this day I have discovered an issue with my design of the ",(0,i.jsx)(n.code,{children:"Solution"})," trait.\nAnd the issue is caused by different types of ",(0,i.jsx)(n.code,{children:"Output"})," for the part 1 and part 2."]}),"\n",(0,i.jsx)(n.p,{children:"Problem is relatively simple and consists of simulating a CPU, I have approached\nit in a following way:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"fn 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",(0,i.jsxs)(n.p,{children:["We just take the instructions, we have some state of the CPU and we execute the\ninstructions one-by-one. Perfect usage of the ",(0,i.jsx)(n.code,{children:"fold"})," (or ",(0,i.jsx)(n.code,{children:"reduce"})," as you may know\nit from other languages)."]}),"\n",(0,i.jsxs)(n.p,{children:["You can also see that we have an ",(0,i.jsx)(n.code,{children:"Output"})," type, so the question is how can we fix\nthat problem. And the answer is very simple and ",(0,i.jsx)(n.em,{children:"functional"}),". Rust allows you to\nhave an ",(0,i.jsx)(n.code,{children:"enumeration"})," that can ",(0,i.jsx)(n.em,{children:"bear"})," some other values apart from the type itself."]}),"\n",(0,i.jsxs)(n.admonition,{type:"tip",children:[(0,i.jsxs)(n.p,{children:["We could've seen something like this with the ",(0,i.jsx)(n.code,{children:"Result"})," type that can be\ndefined as"]}),(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"enum Result {\n Ok(T),\n Err(E)\n}\n"})}),(0,i.jsx)(n.h6,{id:"what-does-that-mean-though",children:"What does that mean though?"}),(0,i.jsxs)(n.p,{children:["When we have an ",(0,i.jsx)(n.code,{children:"Ok"})," value, it has the result itself, and when we get an ",(0,i.jsx)(n.code,{children:"Err"}),"\nvalue, it has the error. This also allows us to handle ",(0,i.jsx)(n.em,{children:"results"})," in a rather\npretty way:"]}),(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:'match do_something(x) {\n Ok(y) => {\n println!("SUCCESS: {}", y);\n },\n Err(y) => {\n eprintln!("ERROR: {}", y);\n }\n}\n'})})]}),"\n",(0,i.jsx)(n.p,{children:"My solution has a following outline:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"fn 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",(0,i.jsxs)(n.p,{children:["You might think that it's a perfectly reasonable thing to do. Yes, ",(0,i.jsx)(n.strong,{children:"but"})," notice\nthat the ",(0,i.jsx)(n.code,{children:"match"})," statement doesn't ",(0,i.jsx)(n.em,{children:"collect"})," the changes in any way and also we\npass ",(0,i.jsx)(n.code,{children:"output"})," by ",(0,i.jsx)(n.code,{children:"&mut"}),", so it is shared across each ",(0,i.jsx)(n.em,{children:"iteration"})," of the ",(0,i.jsx)(n.code,{children:"fold"}),"."]}),"\n",(0,i.jsxs)(n.p,{children:["The dirty and ingenious thing is that ",(0,i.jsx)(n.code,{children:"x"}),"s are passed by ",(0,i.jsx)(n.code,{children:"&mut"})," too and therefore\nthey are directly modified by the helper functions. To sum it up and let it sit"]}),"\n",(0,i.jsxs)(n.blockquote,{children:["\n",(0,i.jsxs)(n.p,{children:["We are ",(0,i.jsx)(n.strong,{children:"collecting"})," the result ",(0,i.jsx)(n.strong,{children:"into"})," an ",(0,i.jsx)(n.strong,{children:"enumeration"})," that is ",(0,i.jsx)(n.strong,{children:"shared"}),"\nacross ",(0,i.jsx)(n.strong,{children:"all"})," iterations of ",(0,i.jsx)(n.code,{children:"fold"}),"."]}),"\n"]}),"\n",(0,i.jsx)(n.h3,{id:"solution-2",children:"Solution"}),"\n",(0,i.jsxs)(n.p,{children:["Similar to ",(0,i.jsx)(n.em,{children:"Day 9"}),", but there are some technical details that can get you."]}),"\n",(0,i.jsx)(n.h2,{id:"day-11-monkey-in-the-middle",children:(0,i.jsx)(n.a,{href:"https://adventofcode.com/2022/day/11",children:"Day 11: Monkey in the Middle"})}),"\n",(0,i.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(n.p,{children:"Simulation of monkeys throwing stuff around and measuring your stress levels\nwhile your stuff is being passed around."})}),"\n",(0,i.jsx)(n.p,{children:"I think I decided to use regular expressions here for the first time, cause\nparsing the input was a pain."}),"\n",(0,i.jsx)(n.p,{children:"Also I didn't expect to implement Euclidean algorithm in Rust\u2026"}),"\n",(0,i.jsx)(n.h3,{id:"solution-3",children:"Solution"}),"\n",(0,i.jsx)(n.p,{children:"Again, 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",(0,i.jsx)(n.h2,{id:"day-12-hill-climbing-algorithm",children:(0,i.jsx)(n.a,{href:"https://adventofcode.com/2022/day/12",children:"Day 12: Hill Climbing Algorithm"})}),"\n",(0,i.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(n.p,{children:"Finding shortest path up the hill and also shortest path down to the ground while\nalso rolling down the hill\u2026"})}),"\n",(0,i.jsxs)(n.p,{children:["As I have said in the ",(0,i.jsx)(n.em,{children:"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",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"fn bfs(\n graph: &[Vec], start: &Position, has_edge: F, is_target: G\n) -> Option\nwhere\n F: Fn(&[Vec], &Position, &Position) -> bool,\n G: Fn(&[Vec], &Position) -> bool\n"})}),"\n",(0,i.jsxs)(n.p,{children:["We pass the initial vertex from the caller and everything else is left to the BFS\nalgorithm, based on the ",(0,i.jsx)(n.code,{children:"has_edge"})," and ",(0,i.jsx)(n.code,{children:"is_target"})," functions."]}),"\n",(0,i.jsxs)(n.p,{children:["This was easy! And that is not very usual in Rust once you want to pass around\nfunctions. ","\ud83d\udc40"]}),"\n",(0,i.jsx)(n.h3,{id:"solution-4",children:"Solution"}),"\n",(0,i.jsxs)(n.p,{children:["Looking for the shortest path\u2026 Must be Dijkstra, right? ",(0,i.jsx)(n.strong,{children:"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, ",(0,i.jsx)(n.strong,{children:"but"})," if you know that\nall connected vertices are in a unit (actually ",(0,i.jsxs)(n.span,{className:"katex",children:[(0,i.jsx)(n.span,{className:"katex-mathml",children:(0,i.jsx)(n.math,{xmlns:"http://www.w3.org/1998/Math/MathML",children:(0,i.jsxs)(n.semantics,{children:[(0,i.jsxs)(n.mrow,{children:[(0,i.jsx)(n.mi,{children:"d"}),(0,i.jsx)(n.mo,{children:"="}),(0,i.jsx)(n.mn,{children:"1"})]}),(0,i.jsx)(n.annotation,{encoding:"application/x-tex",children:"d = 1"})]})})}),(0,i.jsxs)(n.span,{className:"katex-html","aria-hidden":"true",children:[(0,i.jsxs)(n.span,{className:"base",children:[(0,i.jsx)(n.span,{className:"strut",style:{height:"0.6944em"}}),(0,i.jsx)(n.span,{className:"mord mathnormal",children:"d"}),(0,i.jsx)(n.span,{className:"mspace",style:{marginRight:"0.2778em"}}),(0,i.jsx)(n.span,{className:"mrel",children:"="}),(0,i.jsx)(n.span,{className:"mspace",style:{marginRight:"0.2778em"}})]}),(0,i.jsxs)(n.span,{className:"base",children:[(0,i.jsx)(n.span,{className:"strut",style:{height:"0.6444em"}}),(0,i.jsx)(n.span,{className:"mord",children:"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",(0,i.jsx)(n.h2,{id:"day-13-distress-signal",children:(0,i.jsx)(n.a,{href:"https://adventofcode.com/2022/day/13",children:"Day 13: Distress Signal"})}),"\n",(0,i.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(n.p,{children:"Processing packets with structured data from the distress signal."})}),"\n",(0,i.jsxs)(n.p,{children:["You can implement a lot of traits if you want to. It is ",(0,i.jsx)(n.em,{children:"imperative"})," to implement\nordering on the packets. I had a typo, so I also proceeded to implement a ",(0,i.jsx)(n.code,{children:"Display"}),"\ntrait for debugging purposes:"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:'impl 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",(0,i.jsx)(n.h3,{id:"solution-5",children:"Solution"}),"\n",(0,i.jsx)(n.p,{children:"A lot of technical details\u2026 Parsing is nasty too\u2026"}),"\n",(0,i.jsx)(n.h2,{id:"day-14-regolith-reservoir",children:(0,i.jsx)(n.a,{href:"https://adventofcode.com/2022/day/14",children:"Day 14: Regolith Reservoir"})}),"\n",(0,i.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(n.p,{children:"Let's simulate falling sand grain-by-grain."})}),"\n",(0,i.jsxs)(n.p,{children:["Again, both parts are relatively similar with minimal changes, so it is a good\nidea to refactor it a bit. Similar approach to the ",(0,i.jsx)(n.a,{href:"#day-12-hill-climbing-algorithm",children:"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",(0,i.jsx)(n.h3,{id:"solution-6",children:"Solution"}),"\n",(0,i.jsx)(n.p,{children:"Tedious."}),"\n",(0,i.jsx)(n.h2,{id:"post-mortem",children:"Post Mortem"}),"\n",(0,i.jsx)(n.h3,{id:"indexing",children:"Indexing"}),"\n",(0,i.jsxs)(n.p,{children:["I was asked about the indexing after publishing the blog. And truly it is rather\ncomplicated topic, especially after releasing ",(0,i.jsx)(n.code,{children:"SliceIndex"})," trait. I couldn't\nleave it be, so I tried to implement the ",(0,i.jsx)(n.code,{children:"Index"})," and ",(0,i.jsx)(n.code,{children:"IndexMut"})," trait."]}),"\n",(0,i.jsx)(n.admonition,{type:"note",children:(0,i.jsxs)(n.p,{children:["I have also mentioned that the ",(0,i.jsx)(n.code,{children:"SliceIndex"})," trait is ",(0,i.jsx)(n.code,{children:"unsafe"}),", but truth be told,\nonly ",(0,i.jsx)(n.em,{children:"unsafe"})," part are the 2 methods that are named ",(0,i.jsx)(n.code,{children:"*unchecked*"}),". Anyways, I will\nbe implementing the ",(0,i.jsx)(n.code,{children:"Index*"})," traits for now, rather than the ",(0,i.jsx)(n.code,{children:"SliceIndex"}),"."]})}),"\n",(0,i.jsx)(n.p,{children:"It's relatively straightforward\u2026"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"impl Index> for [C]\nwhere\n I: Copy + TryInto,\n >::Error: Debug,\n C: Index,\n{\n type Output = C::Output;\n\n fn index(&self, index: Vector2D) -> &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 IndexMut> for [C]\nwhere\n I: Copy + TryInto,\n >::Error: Debug,\n C: IndexMut,\n{\n fn index_mut(&mut self, index: Vector2D) -> &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",(0,i.jsxs)(n.p,{children:["We can see a lot of similarities to the implementation of ",(0,i.jsx)(n.code,{children:"index"})," and ",(0,i.jsx)(n.code,{children:"index_mut"}),"\nfunctions. In the end, they are 1:1, just wrapped in the trait that provides a\nsyntax sugar for ",(0,i.jsx)(n.code,{children:"container[idx]"}),"."]}),"\n",(0,i.jsxs)(n.admonition,{type:"note",children:[(0,i.jsxs)(n.p,{children:["I have also switched from using the ",(0,i.jsx)(n.code,{children:"TryFrom"})," to ",(0,i.jsx)(n.code,{children:"TryInto"})," trait, since it better\nmatches what we are using, the ",(0,i.jsx)(n.code,{children:".try_into"})," rather than ",(0,i.jsx)(n.code,{children:"usize::try_from"}),"."]}),(0,i.jsxs)(n.p,{children:["Also implementing ",(0,i.jsx)(n.code,{children:"TryFrom"})," automatically provides you with a ",(0,i.jsx)(n.code,{children:"TryInto"})," trait,\nsince it is relatively easy to implement. Just compare the following:"]}),(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"pub trait TryFrom: Sized {\n type Error;\n\n fn try_from(value: T) -> Result;\n}\n\npub trait TryInto: Sized {\n type Error;\n\n fn try_into(self) -> Result;\n}\n"})})]}),"\n",(0,i.jsxs)(n.p,{children:["OK, so we have our trait implemented, we should be able to use ",(0,i.jsx)(n.code,{children:"container[index]"}),",\nright? Yes\u2026 but actually no ","\ud83d\ude26"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{children:"error[E0277]: the type `[std::vec::Vec]` cannot be indexed by `aoc_2022::Vector2D`\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]>` is not implemented for `aoc_2022::Vector2D`\n = note: required for `std::vec::Vec>` to implement `std::ops::Index>`\n\nerror[E0277]: the type `[std::vec::Vec]` cannot be indexed by `aoc_2022::Vector2D`\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]>` is not implemented for `aoc_2022::Vector2D`\n = note: required for `std::vec::Vec>` to implement `std::ops::Index>`\n\nerror[E0277]: the type `[std::vec::Vec]` cannot be indexed by `aoc_2022::Vector2D`\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]>` is not implemented for `aoc_2022::Vector2D`\n = note: required for `std::vec::Vec>` to implement `std::ops::Index>`\n"})}),"\n",(0,i.jsxs)(n.p,{children:["Why? We have it implemented for the slices (",(0,i.jsx)(n.code,{children:"[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 ",(0,i.jsx)(n.code,{children:"&[Vec]"}),", but this is coming from a helper functions that\ntake ",(0,i.jsx)(n.code,{children:"&Vec>"})," instead. And\u2026 we don't implement ",(0,i.jsx)(n.code,{children:"Index"})," and ",(0,i.jsx)(n.code,{children:"IndexMut"})," for\nthose. Just for the slices. \ud83e\udd2f ",(0,i.jsx)(n.em,{children:"What are we going to do about it?"})]}),"\n",(0,i.jsxs)(n.p,{children:["We 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 ",(0,i.jsx)(n.strong,{children:"at all"}),"!"]}),"\n",(0,i.jsx)(n.p,{children:"Implementing the macro can be done in a following way:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"macro_rules! generate_indices {\n ($container:ty) => {\n impl Index> for $container\n where\n I: Copy + TryInto,\n >::Error: Debug,\n C: Index,\n {\n type Output = C::Output;\n\n fn index(&self, index: Vector2D) -> &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 IndexMut> for $container\n where\n I: Copy + TryInto,\n >::Error: Debug,\n C: IndexMut,\n {\n fn index_mut(&mut self, index: Vector2D) -> &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",(0,i.jsx)(n.p,{children:"And now we can simply do"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"generate_indices!(VecDeque);\ngenerate_indices!([C]);\ngenerate_indices!(Vec);\n// generate_indices!([C; N], const N: usize);\n"})}),"\n",(0,i.jsxs)(n.p,{children:["The last type (I took the inspiration from the implementations of the ",(0,i.jsx)(n.code,{children:"Index"})," and\n",(0,i.jsx)(n.code,{children:"IndexMut"})," traits) is a bit problematic, because of the ",(0,i.jsx)(n.code,{children:"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",(0,i.jsx)(n.admonition,{type:"note",children:(0,i.jsxs)(n.p,{children:["If I were to use 2D-indexing over ",(0,i.jsx)(n.code,{children:"[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",(0,i.jsx)(n.h4,{id:"cause-of-the-problem",children:"Cause of the problem"}),"\n",(0,i.jsxs)(n.p,{children:["This issue is relatively funny. If you don't use any type aliases, just the raw\ntypes, you'll get suggested certain changes by the ",(0,i.jsx)(n.em,{children:"clippy"}),". For example if you\nconsider the following piece of code"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:'fn get_sum(nums: &Vec) -> 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",(0,i.jsxs)(n.p,{children:["and you run ",(0,i.jsx)(n.em,{children:"clippy"})," on it, you will get"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{children:'Checking 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 {\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",(0,i.jsx)(n.p,{children:"However, if you introduce a type alias, such as"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"type Numbers = Vec;\n"})}),"\n",(0,i.jsxs)(n.p,{children:["Then ",(0,i.jsx)(n.em,{children:"clippy"})," won't say anything, cause there is literally nothing to suggest.\nHowever the outcome is not the same\u2026"]})]})}function h(e={}){const{wrapper:n}={...(0,s.a)(),...e.components};return n?(0,i.jsx)(n,{...e,children:(0,i.jsx)(c,{...e})}):c(e)}},11151:(e,n,t)=>{t.d(n,{Z:()=>a,a:()=>o});var i=t(67294);const s={},r=i.createContext(s);function o(e){const n=i.useContext(r);return i.useMemo((function(){return"function"==typeof e?e(n):{...n,...e}}),[n,e])}function a(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(s):e.components||s:o(e.components),i.createElement(r.Provider,{value:n},e.children)}}}]); \ No newline at end of file diff --git a/assets/js/3da4b779.1354e52a.js b/assets/js/3da4b779.0020fbfc.js similarity index 89% rename from assets/js/3da4b779.1354e52a.js rename to assets/js/3da4b779.0020fbfc.js index bb12bc2..1c11d1a 100644 --- a/assets/js/3da4b779.1354e52a.js +++ b/assets/js/3da4b779.0020fbfc.js @@ -1 +1 @@ -"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[2177],{28737:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>l,contentTitle:()=>a,default:()=>c,frontMatter:()=>o,metadata:()=>r,toc:()=>d});var i=t(85893),s=t(11151);const o={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:!1},a=void 0,r={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:!0,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:!1},unlisted:!1,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"}},l={authorsImageUrls:[void 0]},d=[{value:"Day 22: Monkey Map",id:"day-22-monkey-map",level:2},{value:"Solution",id:"solution",level:3},{value:"Column iterator",id:"column-iterator",level:4},{value:"Walking around the map",id:"walking-around-the-map",level:4},{value:"Problems",id:"problems",level:4},{value:"Clippy",id:"clippy",level:4},{value:"Day 23: Unstable Diffusion",id:"day-23-unstable-diffusion",level:2},{value:"Solution",id:"solution-1",level:3},{value:"Day 24: Blizzard Basin",id:"day-24-blizzard-basin",level:2},{value:"Solution",id:"solution-2",level:3},{value:"Breakdown",id:"breakdown",level:4},{value:"Evaluating the blizzards",id:"evaluating-the-blizzards",level:4},{value:"Shortest-path algorithm",id:"shortest-path-algorithm",level:4},{value:"Min-heap",id:"min-heap",level:4},{value:"Day 25: Full of Hot Air",id:"day-25-full-of-hot-air",level:2},{value:"Solution",id:"solution-3",level:3},{value:"Converting from &str",id:"converting-from-str",level:4},{value:"Converting to String",id:"converting-to-string",level:4},{value:"Adjusting the code",id:"adjusting-the-code",level:4},{value:"Summary",id:"summary",level:2},{value:"Advent of Code",id:"advent-of-code",level:3},{value:"with Rust",id:"with-rust",level:3}];function h(e){const n={a:"a",admonition:"admonition",annotation:"annotation",code:"code",em:"em",h2:"h2",h3:"h3",h4:"h4",hr:"hr",img:"img",li:"li",math:"math",mi:"mi",mrow:"mrow",p:"p",pre:"pre",semantics:"semantics",span:"span",strong:"strong",ul:"ul",...(0,s.a)(),...e.components};return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)(n.p,{children:["Let's go through the fourth week of ",(0,i.jsx)(n.a,{href:"https://adventofcode.com",children:(0,i.jsx)(n.em,{children:"Advent of Code"})})," in Rust."]}),"\n",(0,i.jsx)(n.h2,{id:"day-22-monkey-map",children:(0,i.jsx)(n.a,{href:"https://adventofcode.com/2022/day/22",children:"Day 22: Monkey Map"})}),"\n",(0,i.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(n.p,{children:"Simulating a movement on a 2D map with given instructions. Map becomes a cube in\nthe 2nd part\u2026"})}),"\n",(0,i.jsx)(n.admonition,{title:"Rant",type:"caution",children:(0,i.jsx)(n.p,{children:"This was the most obnoxious problem of this year\u2026 and a lot of Rust issues have\nbeen hit."})}),"\n",(0,i.jsx)(n.h3,{id:"solution",children:"Solution"}),"\n",(0,i.jsx)(n.p,{children:"It 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",(0,i.jsx)(n.h4,{id:"column-iterator",children:"Column iterator"}),"\n",(0,i.jsxs)(n.p,{children:["In the first part of the problem it was needed to know the boundaries of each\nrow and column, since I stored them in ",(0,i.jsx)(n.code,{children:"Vec>"})," 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 ",(0,i.jsx)(n.code,{children:"Vec"})," element), but not for the columns, since they\nspan multiple rows."]}),"\n",(0,i.jsxs)(n.p,{children:["For this use case I have implemented my own ",(0,i.jsx)(n.em,{children:"column iterator"}),":"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"pub struct ColumnIterator<'a, T> {\n map: &'a [Vec],\n column: usize,\n\n i: usize,\n}\n\nimpl<'a, T> ColumnIterator<'a, T> {\n pub fn new(map: &'a [Vec], 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 {\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",(0,i.jsx)(n.p,{children:"Given this piece of an iterator, it is very easy to factor out the common\nfunctionality between the rows and columns into:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"let mut find_boundaries = |constructor: fn(usize) -> Orientation,\n iterator: &mut dyn Iterator,\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",(0,i.jsx)(n.p,{children:"And then use it as such:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"// 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",(0,i.jsx)(n.h4,{id:"walking-around-the-map",children:"Walking around the map"}),"\n",(0,i.jsxs)(n.p,{children:["Once 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. ",(0,i.jsx)(n.em,{children:"interface"}),") for 2D and 3D walker."]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"trait 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",(0,i.jsx)(n.p,{children:"Each walker maintains its own state and also provides the functions that are\nused during the simulation. The \u201cpromised\u201d methods are separated into:"}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.em,{children:"simulation"}),"-related: that are used during the simulation from the ",(0,i.jsx)(n.code,{children:".fold()"})]}),"\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.em,{children:"movement"}),"-related: just a one method that holds most of the logic differences\nbetween 2D and 3D"]}),"\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.em,{children:"final answer"}),": which extracts the ",(0,i.jsx)(n.em,{children:"proof of solution"})," from the\nimplementation-specific walker"]}),"\n"]}),"\n",(0,i.jsx)(n.p,{children:"Both 2D and 3D versions borrow the original input and therefore you must\nannotate the lifetime of it:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"struct 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",(0,i.jsx)(n.h4,{id:"problems",children:"Problems"}),"\n",(0,i.jsx)(n.p,{children:"I 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",(0,i.jsxs)(n.p,{children:["In 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. ","\ud83d\ude04"]}),"\n",(0,i.jsx)(n.h4,{id:"clippy",children:"Clippy"}),"\n",(0,i.jsx)(n.p,{children:"I have to admit that Clippy was rather helpful here, I'll include two examples\nof rather smart suggestions."}),"\n",(0,i.jsxs)(n.p,{children:["When writing the parsing for this problem, the first thing I have spotted on the\n",(0,i.jsx)(n.code,{children:"char"})," was the ",(0,i.jsx)(n.code,{children:".is_digit()"})," function that takes a radix as a parameter. Clippy\nnoticed that I use ",(0,i.jsx)(n.code,{children:"radix = 10"})," and suggested switching to ",(0,i.jsx)(n.code,{children:".is_ascii_digit()"}),"\nthat does exactly the same thing:"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-diff",children:"- .take_while(|c| c.is_digit(10))\n+ .take_while(|c| c.is_ascii_digit())\n"})}),"\n",(0,i.jsxs)(n.p,{children:["Another useful suggestion appeared when working with the iterators and I wanted\nto get the ",(0,i.jsxs)(n.span,{className:"katex",children:[(0,i.jsx)(n.span,{className:"katex-mathml",children:(0,i.jsx)(n.math,{xmlns:"http://www.w3.org/1998/Math/MathML",children:(0,i.jsxs)(n.semantics,{children:[(0,i.jsx)(n.mrow,{children:(0,i.jsx)(n.mi,{children:"n"})}),(0,i.jsx)(n.annotation,{encoding:"application/x-tex",children:"n"})]})})}),(0,i.jsx)(n.span,{className:"katex-html","aria-hidden":"true",children:(0,i.jsxs)(n.span,{className:"base",children:[(0,i.jsx)(n.span,{className:"strut",style:{height:"0.4306em"}}),(0,i.jsx)(n.span,{className:"mord mathnormal",children:"n"})]})})]}),"-th element from it. You know the ",(0,i.jsx)(n.code,{children:".skip()"}),", you know the\n",(0,i.jsx)(n.code,{children:".next()"}),", just \u201cslap\u201d them together and we're done for ","\ud83d\ude01"," Well, I got\nsuggested to use ",(0,i.jsx)(n.code,{children:".nth()"})," that does exactly the combination of the two mentioned\nmethods on iterators:"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-diff",children:"- match it.clone().skip(skip).next().unwrap() {\n+ match it.clone().nth(skip).unwrap() {\n"})}),"\n",(0,i.jsx)(n.h2,{id:"day-23-unstable-diffusion",children:(0,i.jsx)(n.a,{href:"https://adventofcode.com/2022/day/23",children:"Day 23: Unstable Diffusion"})}),"\n",(0,i.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(n.p,{children:"Simulating movement of elves around with a set of specific rules."})}),"\n",(0,i.jsx)(n.h3,{id:"solution-1",children:"Solution"}),"\n",(0,i.jsxs)(n.p,{children:["There'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","\ud83d\ude09",")."]}),"\n",(0,i.jsx)(n.p,{children:"Although 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",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"fn get_bounds(positions: &Input) -> (Vector2D, Vector2D) {\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::), f(isize::MIN, &max::))\n}\n"})}),"\n",(0,i.jsx)(n.p,{children:"This function returns a pair of 2D vectors that represent opposite points of the\nbounding rectangle of all elves."}),"\n",(0,i.jsxs)(n.p,{children:["You might ask why would we need a closure and the answer is that ",(0,i.jsx)(n.code,{children:"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",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"&dyn Fn(isize, isize) -> isize\n"})}),"\n",(0,i.jsxs)(n.p,{children:["Once we remove the ",(0,i.jsx)(n.code,{children:"dyn"})," keyword, compiler yells at us and also includes a way\nhow to get a more thorough explanation of the error by running"]}),"\n",(0,i.jsx)(n.p,{children:"$ rustc --explain E0782"}),"\n",(0,i.jsx)(n.p,{children:"which shows us"}),"\n",(0,i.jsxs)(n.p,{children:["Trait objects must include the ",(0,i.jsx)(n.code,{children:"dyn"})," keyword."]}),"\n",(0,i.jsx)(n.p,{children:"Erroneous code example:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{children:"trait Foo {}\nfn test(arg: Box) {} // error!\n"})}),"\n",(0,i.jsx)(n.p,{children:"Trait objects are a way to call methods on types that are not known until\nruntime but conform to some trait."}),"\n",(0,i.jsxs)(n.p,{children:["Trait objects should be formed with ",(0,i.jsx)(n.code,{children:"Box"}),", but in the code above\n",(0,i.jsx)(n.code,{children:"dyn"})," is left off."]}),"\n",(0,i.jsxs)(n.p,{children:["This makes it harder to see that ",(0,i.jsx)(n.code,{children:"arg"})," is a trait object and not a\nsimply a heap allocated type called ",(0,i.jsx)(n.code,{children:"Foo"}),"."]}),"\n",(0,i.jsxs)(n.p,{children:["To fix this issue, add ",(0,i.jsx)(n.code,{children:"dyn"})," before the trait name."]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{children:"trait Foo {}\nfn test(arg: Box) {} // ok!\n"})}),"\n",(0,i.jsx)(n.p,{children:"This used to be allowed before edition 2021, but is now an error."}),"\n",(0,i.jsxs)(n.admonition,{title:"Rant",type:"danger",children:[(0,i.jsxs)(n.p,{children:["Not all of the explanations are helpful though, in some cases they might be even\nmore confusing than helpful, since they address ",(0,i.jsx)(n.em,{children:"very simple"})," use cases."]}),(0,i.jsx)(n.p,{children:"As you can see, even in this case there are two sides to the explanations:"}),(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsxs)(n.li,{children:["it explains why you need to use ",(0,i.jsx)(n.code,{children:"dyn"}),", but"]}),"\n",(0,i.jsxs)(n.li,{children:["it still mentions that trait objects need to be heap-allocated via ",(0,i.jsx)(n.code,{children:"Box"}),"\nthat, as you can see in my snippet, ",(0,i.jsx)(n.strong,{children:"does not"})," apply here ","\ud83d\ude04"," IMO it's\ncaused by the fact that we are borrowing it and therefore we don't need to\ncare about the size or whereabouts of it."]}),"\n"]})]}),"\n",(0,i.jsxs)(n.admonition,{title:"C++ parallel",type:"info",children:[(0,i.jsxs)(n.p,{children:["If you dive into the explanation above, you can notice that the ",(0,i.jsx)(n.code,{children:"Box"}),"\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)."]}),(0,i.jsxs)(n.p,{children:["On the other hand, in this case, it doesn't really make much sense, cause you\ncan clearly see that the types ",(0,i.jsx)(n.strong,{children:"are known"})," during the compile-time, which in\nC++ could be easily resolved by templating the helper function."]})]}),"\n",(0,i.jsx)(n.h2,{id:"day-24-blizzard-basin",children:(0,i.jsx)(n.a,{href:"https://adventofcode.com/2022/day/24",children:"Day 24: Blizzard Basin"})}),"\n",(0,i.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(n.p,{children:"Navigating your way through a basin with series of blizzards that move around\nyou as you move."})}),"\n",(0,i.jsx)(n.admonition,{type:"caution",children:(0,i.jsxs)(n.p,{children:["It's second to last day and I went \u201c",(0,i.jsx)(n.em,{children:"bonkers"}),"\u201d on the Rust ","\ud83d\ude04"," Proceed to\nread ",(0,i.jsx)(n.em,{children:"Solution"})," part on your own risk."]})}),"\n",(0,i.jsx)(n.h3,{id:"solution-2",children:"Solution"}),"\n",(0,i.jsx)(n.p,{children:"You 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",(0,i.jsx)(n.h4,{id:"breakdown",children:"Breakdown"}),"\n",(0,i.jsxs)(n.p,{children:["Relatively 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 ",(0,i.jsx)(n.em,{children:"vertex"})," of the graph\nis determined by the position on the map and the ",(0,i.jsx)(n.em,{children:"timestamp"}),". I have chosen to\nuse ",(0,i.jsx)(n.code,{children:"Vector3D"}),", since ",(0,i.jsx)(n.code,{children:"x"})," and ",(0,i.jsx)(n.code,{children:"y"})," attributes can be used for the position\nand, well, let's use ",(0,i.jsx)(n.code,{children:"z"})," for a timestamp, cause why not, right? ","\ud83d\ude09"]}),"\n",(0,i.jsx)(n.h4,{id:"evaluating-the-blizzards",children:"Evaluating the blizzards"}),"\n",(0,i.jsx)(n.admonition,{type:"caution",children:(0,i.jsx)(n.p,{children:"I think that this is the most perverted abuse of the traits in the whole 4 weeks\nof AoC in Rust\u2026"})}),"\n",(0,i.jsxs)(n.p,{children:["The blizzards move along their respective directions in time and loop around in\ntheir respective row/column. Each vertex holds position ",(0,i.jsx)(n.strong,{children:"and"})," time, so we can\n",(0,i.jsx)(n.em,{children:"just"})," index the basin with the vertex itself, right? Yes, we can ","\ud83d\ude08"]}),"\n",(0,i.jsx)(n.admonition,{title:"Fun fact",type:"tip",children:(0,i.jsx)(n.p,{children:"While 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",(0,i.jsxs)(n.p,{children:["I'll skip the boring parts of checking bounds and entry/exit of the basin ","\ud83d\ude09","\nWe can easily calculate positions of the blizzards using a modular arithmetics:"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"impl Index 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",(0,i.jsxs)(n.p,{children:["As 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? ","\ud83d\ude09"]}),"\n",(0,i.jsxs)(n.p,{children:["I couldn't get the ",(0,i.jsx)(n.code,{children:"rustfmt"})," to format the ",(0,i.jsx)(n.code,{children:"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 (",(0,i.jsx)(n.code,{children:"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",(0,i.jsxs)(n.p,{children:["I think it's a very ",(0,i.jsx)(n.em,{children:"nice"})," (and naughty) way how to use the ",(0,i.jsx)(n.code,{children:"Index"})," trait, don't\nyou think?"]}),"\n",(0,i.jsx)(n.h4,{id:"shortest-path-algorithm",children:"Shortest-path algorithm"}),"\n",(0,i.jsxs)(n.p,{children:["For the shortest path you can choose and adjust any of the common shortest-path\nalgorithms, in my case, I have decided to use ",(0,i.jsx)(n.a,{href:"https://en.wikipedia.org/wiki/A*_search_algorithm",children:(0,i.jsx)(n.em,{children:"A*"})})," instead of Dijkstra's\nalgorithm, since it better reflects the ",(0,i.jsx)(n.em,{children:"cost"})," function."]}),"\n",(0,i.jsxs)(n.admonition,{title:"Comparison of costs",type:"info",children:[(0,i.jsxs)(n.p,{children:["With the Dijkstra's algorithm I would proceed with the ",(0,i.jsx)(n.code,{children:"time"})," attribute used as\na priority for the queue."]}),(0,i.jsxs)(n.p,{children:["Whereas with the ",(0,i.jsx)(n.em,{children:"A*"}),", I have chosen to use both time and Manhattan distance\nthat promotes vertices closer to the exit ",(0,i.jsx)(n.strong,{children:"and"})," with a minimum time taken."]})]}),"\n",(0,i.jsxs)(n.p,{children:["Cost function is, of course, a closure ","\ud83d\ude09"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"let cost = |p: Position| p.z() as usize + exit.y().abs_diff(p.y()) + exit.x().abs_diff(p.x());\n"})}),"\n",(0,i.jsx)(n.p,{children:"And 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",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"let 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",(0,i.jsx)(n.h4,{id:"min-heap",children:"Min-heap"}),"\n",(0,i.jsxs)(n.p,{children:["In 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 ",(0,i.jsx)(n.a,{href:"https://doc.rust-lang.org/std/collections/struct.BinaryHeap.html",children:(0,i.jsx)(n.code,{children:"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 ",(0,i.jsx)(n.a,{href:"https://doc.rust-lang.org/std/cmp/struct.Reverse.html",children:(0,i.jsx)(n.code,{children:"Reverse"})})," (as is even showed in the linked ",(0,i.jsxs)(n.a,{href:"https://doc.rust-lang.org/std/collections/struct.BinaryHeap.html#min-heap",children:["docs of\nthe ",(0,i.jsx)(n.code,{children:"BinaryHeap"})]}),"). However the wrapping affects the type of the heap and also\npopping the most prioritized elements yields values wrapped in the ",(0,i.jsx)(n.code,{children:"Reverse"}),"."]}),"\n",(0,i.jsx)(n.p,{children:"For 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",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"use std::cmp::{Ord, Reverse};\nuse std::collections::BinaryHeap;\n\npub struct MinHeap {\n heap: BinaryHeap>,\n}\n\nimpl MinHeap {\n pub fn new() -> MinHeap {\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 {\n self.heap.pop().map(|Reverse(x)| x)\n }\n}\n\nimpl Default for MinHeap {\n fn default() -> Self {\n Self::new()\n }\n}\n"})}),"\n",(0,i.jsx)(n.p,{children:"Rest is just the algorithm implementation which is not that interesting."}),"\n",(0,i.jsx)(n.h2,{id:"day-25-full-of-hot-air",children:(0,i.jsx)(n.a,{href:"https://adventofcode.com/2022/day/25",children:"Day 25: Full of Hot Air"})}),"\n",(0,i.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,i.jsxs)(n.p,{children:["Playing around with a numbers in a ",(0,i.jsx)(n.em,{children:"special"})," base."]})}),"\n",(0,i.jsxs)(n.p,{children:["Getting flashbacks to the ",(0,i.jsx)(n.em,{children:"IB111 Foundations of Programming"}),"\u2026 Very nice \u201cproblem\u201d\nwith a rather easy solution, as the last day always seems to be."]}),"\n",(0,i.jsx)(n.h3,{id:"solution-3",children:"Solution"}),"\n",(0,i.jsxs)(n.p,{children:["Implementing 2 functions, converting from the ",(0,i.jsx)(n.em,{children:"SNAFU base"})," and back to the ",(0,i.jsx)(n.em,{children:"SNAFU"}),"\n",(0,i.jsx)(n.em,{children:"base"})," representation. Let's do a bit more though! I have implemented two functions:"]}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsx)(n.li,{children:(0,i.jsx)(n.code,{children:"from_snafu"})}),"\n",(0,i.jsx)(n.li,{children:(0,i.jsx)(n.code,{children:"to_snafu"})}),"\n"]}),"\n",(0,i.jsx)(n.p,{children:"Now 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",(0,i.jsx)(n.p,{children:"Let's start with a structure:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]\nstruct SNAFU {\n value: i64,\n}\n"})}),"\n",(0,i.jsxs)(n.h4,{id:"converting-from-str",children:["Converting from ",(0,i.jsx)(n.code,{children:"&str"})]}),"\n",(0,i.jsxs)(n.p,{children:["We will start by implementing the ",(0,i.jsx)(n.code,{children:"FromStr"})," trait that will help us parse our input.\nThis is rather simple, I can just take the ",(0,i.jsx)(n.code,{children:"from_snafu"})," function, copy-paste it\ninto the ",(0,i.jsx)(n.code,{children:"from_str"})," method and the number I get will be wrapped in ",(0,i.jsx)(n.code,{children:"Result"})," and\n",(0,i.jsx)(n.code,{children:"SNAFU"})," structure."]}),"\n",(0,i.jsxs)(n.h4,{id:"converting-to-string",children:["Converting to ",(0,i.jsx)(n.code,{children:"String"})]}),"\n",(0,i.jsxs)(n.p,{children:["This 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 ",(0,i.jsx)(n.code,{children:"ToString"})," trait is automatically implemented\nfor any type that implements ",(0,i.jsx)(n.code,{children:"Display"})," trait."]}),"\n",(0,i.jsxs)(n.p,{children:["Let's implement the ",(0,i.jsx)(n.code,{children:"Display"})," trait then. We should be able to use the ",(0,i.jsx)(n.code,{children:"to_snafu"}),"\nfunction and just take the ",(0,i.jsx)(n.code,{children:"self.value"})," from the ",(0,i.jsx)(n.code,{children:"SNAFU"})," structure."]}),"\n",(0,i.jsxs)(n.p,{children:["And for the convenience of tests, we can also implement a rather simple ",(0,i.jsx)(n.code,{children:"From"}),"\ntrait for the ",(0,i.jsx)(n.code,{children:"SNAFU"}),"."]}),"\n",(0,i.jsx)(n.h4,{id:"adjusting-the-code",children:"Adjusting the code"}),"\n",(0,i.jsx)(n.p,{children:"After those changes we need to adjust the code and tests."}),"\n",(0,i.jsx)(n.p,{children:"Parsing of the input is very easy, before we have used the lines, now we parse\neverything:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-diff",children:" fn parse_input>(pathname: P) -> Input {\n- file_to_lines(pathname)\n+ file_to_structs(pathname)\n }\n"})}),"\n",(0,i.jsx)(n.p,{children:"Part 1 needs to be adjusted a bit too:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-diff",children:" 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::()).to_string()\n }\n"})}),"\n",(0,i.jsx)(n.p,{children:"You can also see that it simplifies the meaning a bit and it is more explicit than\nthe previous versions."}),"\n",(0,i.jsx)(n.p,{children:"And for the tests:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-diff",children:" #[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::().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",(0,i.jsx)(n.h2,{id:"summary",children:"Summary"}),"\n",(0,i.jsx)(n.p,{children:"Let's wrap the whole thing up! Keeping in mind both AoC and the Rust\u2026"}),"\n",(0,i.jsx)(n.p,{children:(0,i.jsx)(n.img,{alt:"Finished advent calendar :smile:",src:t(63321).Z+"",width:"2417",height:"1984"})}),"\n",(0,i.jsx)(n.h3,{id:"advent-of-code",children:"Advent of Code"}),"\n",(0,i.jsxs)(n.p,{children:["This year was quite fun, even though most of the solutions and posts came in\nlater on (",(0,i.jsx)(n.em,{children:"cough"})," in '23 ",(0,i.jsx)(n.em,{children:"cough"}),"). Day 22 was the most obnoxious one\u2026 And also\nit feels like I used priority queues and tree data structures ",(0,i.jsx)(n.strong,{children:"a lot"})," ","\ud83d\udc40"]}),"\n",(0,i.jsx)(n.h3,{id:"with-rust",children:"with Rust"}),"\n",(0,i.jsx)(n.p,{children:"I 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",(0,i.jsx)(n.p,{children:"Building 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",(0,i.jsx)(n.p,{children:"I am definitely much more aware of the basic things that bloated Python is\nmissing, yet Rust has them\u2026"}),"\n",(0,i.jsxs)(n.p,{children:["Using explicit types and writing down placeholder functions with ",(0,i.jsx)(n.code,{children:"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",(0,i.jsx)(n.p,{children:"I 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",(0,i.jsx)(n.p,{children:"I 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",(0,i.jsxs)(n.p,{children:["tl;dr Relatively pleasant language until you hit brick wall ","\ud83d\ude09"]}),"\n",(0,i.jsx)(n.hr,{}),"\n",(0,i.jsxs)(n.p,{children:["See you next year! Maybe in Rust, maybe not ","\ud83d\ude43"]})]})}function c(e={}){const{wrapper:n}={...(0,s.a)(),...e.components};return n?(0,i.jsx)(n,{...e,children:(0,i.jsx)(h,{...e})}):h(e)}},63321:(e,n,t)=>{t.d(n,{Z:()=>i});const i=t.p+"assets/images/calendar-f891b624f3e0efb34bba582100a7d8df.png"},11151:(e,n,t)=>{t.d(n,{Z:()=>r,a:()=>a});var i=t(67294);const s={},o=i.createContext(s);function a(e){const n=i.useContext(o);return i.useMemo((function(){return"function"==typeof e?e(n):{...n,...e}}),[n,e])}function r(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(s):e.components||s:a(e.components),i.createElement(o.Provider,{value:n},e.children)}}}]); \ No newline at end of file +"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[2177],{28737:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>l,contentTitle:()=>a,default:()=>c,frontMatter:()=>o,metadata:()=>r,toc:()=>d});var i=t(85893),s=t(11151);const o={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:!1},a=void 0,r={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:!0,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:!1},unlisted:!1,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"}},l={authorsImageUrls:[void 0]},d=[{value:"Day 22: Monkey Map",id:"day-22-monkey-map",level:2},{value:"Solution",id:"solution",level:3},{value:"Column iterator",id:"column-iterator",level:4},{value:"Walking around the map",id:"walking-around-the-map",level:4},{value:"Problems",id:"problems",level:4},{value:"Clippy",id:"clippy",level:4},{value:"Day 23: Unstable Diffusion",id:"day-23-unstable-diffusion",level:2},{value:"Solution",id:"solution-1",level:3},{value:"Day 24: Blizzard Basin",id:"day-24-blizzard-basin",level:2},{value:"Solution",id:"solution-2",level:3},{value:"Breakdown",id:"breakdown",level:4},{value:"Evaluating the blizzards",id:"evaluating-the-blizzards",level:4},{value:"Shortest-path algorithm",id:"shortest-path-algorithm",level:4},{value:"Min-heap",id:"min-heap",level:4},{value:"Day 25: Full of Hot Air",id:"day-25-full-of-hot-air",level:2},{value:"Solution",id:"solution-3",level:3},{value:"Converting from &str",id:"converting-from-str",level:4},{value:"Converting to String",id:"converting-to-string",level:4},{value:"Adjusting the code",id:"adjusting-the-code",level:4},{value:"Summary",id:"summary",level:2},{value:"Advent of Code",id:"advent-of-code",level:3},{value:"with Rust",id:"with-rust",level:3}];function h(e){const n={a:"a",admonition:"admonition",annotation:"annotation",code:"code",em:"em",h2:"h2",h3:"h3",h4:"h4",hr:"hr",img:"img",li:"li",math:"math",mi:"mi",mrow:"mrow",p:"p",pre:"pre",semantics:"semantics",span:"span",strong:"strong",ul:"ul",...(0,s.a)(),...e.components};return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)(n.p,{children:["Let's go through the fourth week of ",(0,i.jsx)(n.a,{href:"https://adventofcode.com",children:(0,i.jsx)(n.em,{children:"Advent of Code"})})," in Rust."]}),"\n",(0,i.jsx)(n.h2,{id:"day-22-monkey-map",children:(0,i.jsx)(n.a,{href:"https://adventofcode.com/2022/day/22",children:"Day 22: Monkey Map"})}),"\n",(0,i.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(n.p,{children:"Simulating a movement on a 2D map with given instructions. Map becomes a cube in\nthe 2nd part\u2026"})}),"\n",(0,i.jsx)(n.admonition,{title:"Rant",type:"caution",children:(0,i.jsx)(n.p,{children:"This was the most obnoxious problem of this year\u2026 and a lot of Rust issues have\nbeen hit."})}),"\n",(0,i.jsx)(n.h3,{id:"solution",children:"Solution"}),"\n",(0,i.jsx)(n.p,{children:"It 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",(0,i.jsx)(n.h4,{id:"column-iterator",children:"Column iterator"}),"\n",(0,i.jsxs)(n.p,{children:["In the first part of the problem it was needed to know the boundaries of each\nrow and column, since I stored them in ",(0,i.jsx)(n.code,{children:"Vec>"})," 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 ",(0,i.jsx)(n.code,{children:"Vec"})," element), but not for the columns, since they\nspan multiple rows."]}),"\n",(0,i.jsxs)(n.p,{children:["For this use case I have implemented my own ",(0,i.jsx)(n.em,{children:"column iterator"}),":"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"pub struct ColumnIterator<'a, T> {\n map: &'a [Vec],\n column: usize,\n\n i: usize,\n}\n\nimpl<'a, T> ColumnIterator<'a, T> {\n pub fn new(map: &'a [Vec], 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 {\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",(0,i.jsx)(n.p,{children:"Given this piece of an iterator, it is very easy to factor out the common\nfunctionality between the rows and columns into:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"let mut find_boundaries = |constructor: fn(usize) -> Orientation,\n iterator: &mut dyn Iterator,\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",(0,i.jsx)(n.p,{children:"And then use it as such:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"// 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",(0,i.jsx)(n.h4,{id:"walking-around-the-map",children:"Walking around the map"}),"\n",(0,i.jsxs)(n.p,{children:["Once 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. ",(0,i.jsx)(n.em,{children:"interface"}),") for 2D and 3D walker."]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"trait 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",(0,i.jsx)(n.p,{children:"Each walker maintains its own state and also provides the functions that are\nused during the simulation. The \u201cpromised\u201d methods are separated into:"}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.em,{children:"simulation"}),"-related: that are used during the simulation from the ",(0,i.jsx)(n.code,{children:".fold()"})]}),"\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.em,{children:"movement"}),"-related: just a one method that holds most of the logic differences\nbetween 2D and 3D"]}),"\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.em,{children:"final answer"}),": which extracts the ",(0,i.jsx)(n.em,{children:"proof of solution"})," from the\nimplementation-specific walker"]}),"\n"]}),"\n",(0,i.jsx)(n.p,{children:"Both 2D and 3D versions borrow the original input and therefore you must\nannotate the lifetime of it:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"struct 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",(0,i.jsx)(n.h4,{id:"problems",children:"Problems"}),"\n",(0,i.jsx)(n.p,{children:"I 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",(0,i.jsxs)(n.p,{children:["In 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. ","\ud83d\ude04"]}),"\n",(0,i.jsx)(n.h4,{id:"clippy",children:"Clippy"}),"\n",(0,i.jsx)(n.p,{children:"I have to admit that Clippy was rather helpful here, I'll include two examples\nof rather smart suggestions."}),"\n",(0,i.jsxs)(n.p,{children:["When writing the parsing for this problem, the first thing I have spotted on the\n",(0,i.jsx)(n.code,{children:"char"})," was the ",(0,i.jsx)(n.code,{children:".is_digit()"})," function that takes a radix as a parameter. Clippy\nnoticed that I use ",(0,i.jsx)(n.code,{children:"radix = 10"})," and suggested switching to ",(0,i.jsx)(n.code,{children:".is_ascii_digit()"}),"\nthat does exactly the same thing:"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-diff",children:"- .take_while(|c| c.is_digit(10))\n+ .take_while(|c| c.is_ascii_digit())\n"})}),"\n",(0,i.jsxs)(n.p,{children:["Another useful suggestion appeared when working with the iterators and I wanted\nto get the ",(0,i.jsxs)(n.span,{className:"katex",children:[(0,i.jsx)(n.span,{className:"katex-mathml",children:(0,i.jsx)(n.math,{xmlns:"http://www.w3.org/1998/Math/MathML",children:(0,i.jsxs)(n.semantics,{children:[(0,i.jsx)(n.mrow,{children:(0,i.jsx)(n.mi,{children:"n"})}),(0,i.jsx)(n.annotation,{encoding:"application/x-tex",children:"n"})]})})}),(0,i.jsx)(n.span,{className:"katex-html","aria-hidden":"true",children:(0,i.jsxs)(n.span,{className:"base",children:[(0,i.jsx)(n.span,{className:"strut",style:{height:"0.4306em"}}),(0,i.jsx)(n.span,{className:"mord mathnormal",children:"n"})]})})]}),"-th element from it. You know the ",(0,i.jsx)(n.code,{children:".skip()"}),", you know the\n",(0,i.jsx)(n.code,{children:".next()"}),", just \u201cslap\u201d them together and we're done for ","\ud83d\ude01"," Well, I got\nsuggested to use ",(0,i.jsx)(n.code,{children:".nth()"})," that does exactly the combination of the two mentioned\nmethods on iterators:"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-diff",children:"- match it.clone().skip(skip).next().unwrap() {\n+ match it.clone().nth(skip).unwrap() {\n"})}),"\n",(0,i.jsx)(n.h2,{id:"day-23-unstable-diffusion",children:(0,i.jsx)(n.a,{href:"https://adventofcode.com/2022/day/23",children:"Day 23: Unstable Diffusion"})}),"\n",(0,i.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(n.p,{children:"Simulating movement of elves around with a set of specific rules."})}),"\n",(0,i.jsx)(n.h3,{id:"solution-1",children:"Solution"}),"\n",(0,i.jsxs)(n.p,{children:["There'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","\ud83d\ude09",")."]}),"\n",(0,i.jsx)(n.p,{children:"Although 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",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"fn get_bounds(positions: &Input) -> (Vector2D, Vector2D) {\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::), f(isize::MIN, &max::))\n}\n"})}),"\n",(0,i.jsx)(n.p,{children:"This function returns a pair of 2D vectors that represent opposite points of the\nbounding rectangle of all elves."}),"\n",(0,i.jsxs)(n.p,{children:["You might ask why would we need a closure and the answer is that ",(0,i.jsx)(n.code,{children:"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",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"&dyn Fn(isize, isize) -> isize\n"})}),"\n",(0,i.jsxs)(n.p,{children:["Once we remove the ",(0,i.jsx)(n.code,{children:"dyn"})," keyword, compiler yells at us and also includes a way\nhow to get a more thorough explanation of the error by running"]}),"\n",(0,i.jsx)(n.p,{children:"$ rustc --explain E0782"}),"\n",(0,i.jsx)(n.p,{children:"which shows us"}),"\n",(0,i.jsxs)(n.p,{children:["Trait objects must include the ",(0,i.jsx)(n.code,{children:"dyn"})," keyword."]}),"\n",(0,i.jsx)(n.p,{children:"Erroneous code example:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{children:"trait Foo {}\nfn test(arg: Box) {} // error!\n"})}),"\n",(0,i.jsx)(n.p,{children:"Trait objects are a way to call methods on types that are not known until\nruntime but conform to some trait."}),"\n",(0,i.jsxs)(n.p,{children:["Trait objects should be formed with ",(0,i.jsx)(n.code,{children:"Box"}),", but in the code above\n",(0,i.jsx)(n.code,{children:"dyn"})," is left off."]}),"\n",(0,i.jsxs)(n.p,{children:["This makes it harder to see that ",(0,i.jsx)(n.code,{children:"arg"})," is a trait object and not a\nsimply a heap allocated type called ",(0,i.jsx)(n.code,{children:"Foo"}),"."]}),"\n",(0,i.jsxs)(n.p,{children:["To fix this issue, add ",(0,i.jsx)(n.code,{children:"dyn"})," before the trait name."]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{children:"trait Foo {}\nfn test(arg: Box) {} // ok!\n"})}),"\n",(0,i.jsx)(n.p,{children:"This used to be allowed before edition 2021, but is now an error."}),"\n",(0,i.jsxs)(n.admonition,{title:"Rant",type:"danger",children:[(0,i.jsxs)(n.p,{children:["Not all of the explanations are helpful though, in some cases they might be even\nmore confusing than helpful, since they address ",(0,i.jsx)(n.em,{children:"very simple"})," use cases."]}),(0,i.jsx)(n.p,{children:"As you can see, even in this case there are two sides to the explanations:"}),(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsxs)(n.li,{children:["it explains why you need to use ",(0,i.jsx)(n.code,{children:"dyn"}),", but"]}),"\n",(0,i.jsxs)(n.li,{children:["it still mentions that trait objects need to be heap-allocated via ",(0,i.jsx)(n.code,{children:"Box"}),"\nthat, as you can see in my snippet, ",(0,i.jsx)(n.strong,{children:"does not"})," apply here ","\ud83d\ude04"," IMO it's\ncaused by the fact that we are borrowing it and therefore we don't need to\ncare about the size or whereabouts of it."]}),"\n"]})]}),"\n",(0,i.jsxs)(n.admonition,{title:"C++ parallel",type:"info",children:[(0,i.jsxs)(n.p,{children:["If you dive into the explanation above, you can notice that the ",(0,i.jsx)(n.code,{children:"Box"}),"\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)."]}),(0,i.jsxs)(n.p,{children:["On the other hand, in this case, it doesn't really make much sense, cause you\ncan clearly see that the types ",(0,i.jsx)(n.strong,{children:"are known"})," during the compile-time, which in\nC++ could be easily resolved by templating the helper function."]})]}),"\n",(0,i.jsx)(n.h2,{id:"day-24-blizzard-basin",children:(0,i.jsx)(n.a,{href:"https://adventofcode.com/2022/day/24",children:"Day 24: Blizzard Basin"})}),"\n",(0,i.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(n.p,{children:"Navigating your way through a basin with series of blizzards that move around\nyou as you move."})}),"\n",(0,i.jsx)(n.admonition,{type:"caution",children:(0,i.jsxs)(n.p,{children:["It's second to last day and I went \u201c",(0,i.jsx)(n.em,{children:"bonkers"}),"\u201d on the Rust ","\ud83d\ude04"," Proceed to\nread ",(0,i.jsx)(n.em,{children:"Solution"})," part on your own risk."]})}),"\n",(0,i.jsx)(n.h3,{id:"solution-2",children:"Solution"}),"\n",(0,i.jsx)(n.p,{children:"You 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",(0,i.jsx)(n.h4,{id:"breakdown",children:"Breakdown"}),"\n",(0,i.jsxs)(n.p,{children:["Relatively 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 ",(0,i.jsx)(n.em,{children:"vertex"})," of the graph\nis determined by the position on the map and the ",(0,i.jsx)(n.em,{children:"timestamp"}),". I have chosen to\nuse ",(0,i.jsx)(n.code,{children:"Vector3D"}),", since ",(0,i.jsx)(n.code,{children:"x"})," and ",(0,i.jsx)(n.code,{children:"y"})," attributes can be used for the position\nand, well, let's use ",(0,i.jsx)(n.code,{children:"z"})," for a timestamp, cause why not, right? ","\ud83d\ude09"]}),"\n",(0,i.jsx)(n.h4,{id:"evaluating-the-blizzards",children:"Evaluating the blizzards"}),"\n",(0,i.jsx)(n.admonition,{type:"caution",children:(0,i.jsx)(n.p,{children:"I think that this is the most perverted abuse of the traits in the whole 4 weeks\nof AoC in Rust\u2026"})}),"\n",(0,i.jsxs)(n.p,{children:["The blizzards move along their respective directions in time and loop around in\ntheir respective row/column. Each vertex holds position ",(0,i.jsx)(n.strong,{children:"and"})," time, so we can\n",(0,i.jsx)(n.em,{children:"just"})," index the basin with the vertex itself, right? Yes, we can ","\ud83d\ude08"]}),"\n",(0,i.jsx)(n.admonition,{title:"Fun fact",type:"tip",children:(0,i.jsx)(n.p,{children:"While 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",(0,i.jsxs)(n.p,{children:["I'll skip the boring parts of checking bounds and entry/exit of the basin ","\ud83d\ude09","\nWe can easily calculate positions of the blizzards using a modular arithmetics:"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"impl Index 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",(0,i.jsxs)(n.p,{children:["As 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? ","\ud83d\ude09"]}),"\n",(0,i.jsxs)(n.p,{children:["I couldn't get the ",(0,i.jsx)(n.code,{children:"rustfmt"})," to format the ",(0,i.jsx)(n.code,{children:"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 (",(0,i.jsx)(n.code,{children:"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",(0,i.jsxs)(n.p,{children:["I think it's a very ",(0,i.jsx)(n.em,{children:"nice"})," (and naughty) way how to use the ",(0,i.jsx)(n.code,{children:"Index"})," trait, don't\nyou think?"]}),"\n",(0,i.jsx)(n.h4,{id:"shortest-path-algorithm",children:"Shortest-path algorithm"}),"\n",(0,i.jsxs)(n.p,{children:["For the shortest path you can choose and adjust any of the common shortest-path\nalgorithms, in my case, I have decided to use ",(0,i.jsx)(n.a,{href:"https://en.wikipedia.org/wiki/A*_search_algorithm",children:(0,i.jsx)(n.em,{children:"A*"})})," instead of Dijkstra's\nalgorithm, since it better reflects the ",(0,i.jsx)(n.em,{children:"cost"})," function."]}),"\n",(0,i.jsxs)(n.admonition,{title:"Comparison of costs",type:"info",children:[(0,i.jsxs)(n.p,{children:["With the Dijkstra's algorithm I would proceed with the ",(0,i.jsx)(n.code,{children:"time"})," attribute used as\na priority for the queue."]}),(0,i.jsxs)(n.p,{children:["Whereas with the ",(0,i.jsx)(n.em,{children:"A*"}),", I have chosen to use both time and Manhattan distance\nthat promotes vertices closer to the exit ",(0,i.jsx)(n.strong,{children:"and"})," with a minimum time taken."]})]}),"\n",(0,i.jsxs)(n.p,{children:["Cost function is, of course, a closure ","\ud83d\ude09"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"let cost = |p: Position| p.z() as usize + exit.y().abs_diff(p.y()) + exit.x().abs_diff(p.x());\n"})}),"\n",(0,i.jsx)(n.p,{children:"And 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",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"let 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",(0,i.jsx)(n.h4,{id:"min-heap",children:"Min-heap"}),"\n",(0,i.jsxs)(n.p,{children:["In 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 ",(0,i.jsx)(n.a,{href:"https://doc.rust-lang.org/std/collections/struct.BinaryHeap.html",children:(0,i.jsx)(n.code,{children:"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 ",(0,i.jsx)(n.a,{href:"https://doc.rust-lang.org/std/cmp/struct.Reverse.html",children:(0,i.jsx)(n.code,{children:"Reverse"})})," (as is even showed in the linked ",(0,i.jsxs)(n.a,{href:"https://doc.rust-lang.org/std/collections/struct.BinaryHeap.html#min-heap",children:["docs of\nthe ",(0,i.jsx)(n.code,{children:"BinaryHeap"})]}),"). However the wrapping affects the type of the heap and also\npopping the most prioritized elements yields values wrapped in the ",(0,i.jsx)(n.code,{children:"Reverse"}),"."]}),"\n",(0,i.jsx)(n.p,{children:"For 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",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"use std::cmp::{Ord, Reverse};\nuse std::collections::BinaryHeap;\n\npub struct MinHeap {\n heap: BinaryHeap>,\n}\n\nimpl MinHeap {\n pub fn new() -> MinHeap {\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 {\n self.heap.pop().map(|Reverse(x)| x)\n }\n}\n\nimpl Default for MinHeap {\n fn default() -> Self {\n Self::new()\n }\n}\n"})}),"\n",(0,i.jsx)(n.p,{children:"Rest is just the algorithm implementation which is not that interesting."}),"\n",(0,i.jsx)(n.h2,{id:"day-25-full-of-hot-air",children:(0,i.jsx)(n.a,{href:"https://adventofcode.com/2022/day/25",children:"Day 25: Full of Hot Air"})}),"\n",(0,i.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,i.jsxs)(n.p,{children:["Playing around with a numbers in a ",(0,i.jsx)(n.em,{children:"special"})," base."]})}),"\n",(0,i.jsxs)(n.p,{children:["Getting flashbacks to the ",(0,i.jsx)(n.em,{children:"IB111 Foundations of Programming"}),"\u2026 Very nice \u201cproblem\u201d\nwith a rather easy solution, as the last day always seems to be."]}),"\n",(0,i.jsx)(n.h3,{id:"solution-3",children:"Solution"}),"\n",(0,i.jsxs)(n.p,{children:["Implementing 2 functions, converting from the ",(0,i.jsx)(n.em,{children:"SNAFU base"})," and back to the ",(0,i.jsx)(n.em,{children:"SNAFU"}),"\n",(0,i.jsx)(n.em,{children:"base"})," representation. Let's do a bit more though! I have implemented two functions:"]}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsx)(n.li,{children:(0,i.jsx)(n.code,{children:"from_snafu"})}),"\n",(0,i.jsx)(n.li,{children:(0,i.jsx)(n.code,{children:"to_snafu"})}),"\n"]}),"\n",(0,i.jsx)(n.p,{children:"Now 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",(0,i.jsx)(n.p,{children:"Let's start with a structure:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-rust",children:"#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]\nstruct SNAFU {\n value: i64,\n}\n"})}),"\n",(0,i.jsxs)(n.h4,{id:"converting-from-str",children:["Converting from ",(0,i.jsx)(n.code,{children:"&str"})]}),"\n",(0,i.jsxs)(n.p,{children:["We will start by implementing the ",(0,i.jsx)(n.code,{children:"FromStr"})," trait that will help us parse our input.\nThis is rather simple, I can just take the ",(0,i.jsx)(n.code,{children:"from_snafu"})," function, copy-paste it\ninto the ",(0,i.jsx)(n.code,{children:"from_str"})," method and the number I get will be wrapped in ",(0,i.jsx)(n.code,{children:"Result"})," and\n",(0,i.jsx)(n.code,{children:"SNAFU"})," structure."]}),"\n",(0,i.jsxs)(n.h4,{id:"converting-to-string",children:["Converting to ",(0,i.jsx)(n.code,{children:"String"})]}),"\n",(0,i.jsxs)(n.p,{children:["This 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 ",(0,i.jsx)(n.code,{children:"ToString"})," trait is automatically implemented\nfor any type that implements ",(0,i.jsx)(n.code,{children:"Display"})," trait."]}),"\n",(0,i.jsxs)(n.p,{children:["Let's implement the ",(0,i.jsx)(n.code,{children:"Display"})," trait then. We should be able to use the ",(0,i.jsx)(n.code,{children:"to_snafu"}),"\nfunction and just take the ",(0,i.jsx)(n.code,{children:"self.value"})," from the ",(0,i.jsx)(n.code,{children:"SNAFU"})," structure."]}),"\n",(0,i.jsxs)(n.p,{children:["And for the convenience of tests, we can also implement a rather simple ",(0,i.jsx)(n.code,{children:"From"}),"\ntrait for the ",(0,i.jsx)(n.code,{children:"SNAFU"}),"."]}),"\n",(0,i.jsx)(n.h4,{id:"adjusting-the-code",children:"Adjusting the code"}),"\n",(0,i.jsx)(n.p,{children:"After those changes we need to adjust the code and tests."}),"\n",(0,i.jsx)(n.p,{children:"Parsing of the input is very easy, before we have used the lines, now we parse\neverything:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-diff",children:" fn parse_input>(pathname: P) -> Input {\n- file_to_lines(pathname)\n+ file_to_structs(pathname)\n }\n"})}),"\n",(0,i.jsx)(n.p,{children:"Part 1 needs to be adjusted a bit too:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-diff",children:" 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::()).to_string()\n }\n"})}),"\n",(0,i.jsx)(n.p,{children:"You can also see that it simplifies the meaning a bit and it is more explicit than\nthe previous versions."}),"\n",(0,i.jsx)(n.p,{children:"And for the tests:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-diff",children:" #[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::().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",(0,i.jsx)(n.h2,{id:"summary",children:"Summary"}),"\n",(0,i.jsx)(n.p,{children:"Let's wrap the whole thing up! Keeping in mind both AoC and the Rust\u2026"}),"\n",(0,i.jsx)(n.p,{children:(0,i.jsx)(n.img,{alt:"Finished advent calendar :smile:",src:t(63321).Z+"",width:"2417",height:"1984"})}),"\n",(0,i.jsx)(n.h3,{id:"advent-of-code",children:"Advent of Code"}),"\n",(0,i.jsxs)(n.p,{children:["This year was quite fun, even though most of the solutions and posts came in\nlater on (",(0,i.jsx)(n.em,{children:"cough"})," in '23 ",(0,i.jsx)(n.em,{children:"cough"}),"). Day 22 was the most obnoxious one\u2026 And also\nit feels like I used priority queues and tree data structures ",(0,i.jsx)(n.strong,{children:"a lot"})," ","\ud83d\udc40"]}),"\n",(0,i.jsx)(n.h3,{id:"with-rust",children:"with Rust"}),"\n",(0,i.jsx)(n.p,{children:"I 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",(0,i.jsx)(n.p,{children:"Building 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",(0,i.jsx)(n.p,{children:"I am definitely much more aware of the basic things that bloated Python is\nmissing, yet Rust has them\u2026"}),"\n",(0,i.jsxs)(n.p,{children:["Using explicit types and writing down placeholder functions with ",(0,i.jsx)(n.code,{children:"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",(0,i.jsx)(n.p,{children:"I 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",(0,i.jsx)(n.p,{children:"I 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",(0,i.jsxs)(n.p,{children:["tl;dr Relatively pleasant language until you hit brick wall ","\ud83d\ude09"]}),"\n",(0,i.jsx)(n.hr,{}),"\n",(0,i.jsxs)(n.p,{children:["See you next year! Maybe in Rust, maybe not ","\ud83d\ude43"]})]})}function c(e={}){const{wrapper:n}={...(0,s.a)(),...e.components};return n?(0,i.jsx)(n,{...e,children:(0,i.jsx)(h,{...e})}):h(e)}},63321:(e,n,t)=>{t.d(n,{Z:()=>i});const i=t.p+"assets/images/calendar-f891b624f3e0efb34bba582100a7d8df.png"},11151:(e,n,t)=>{t.d(n,{Z:()=>r,a:()=>a});var i=t(67294);const s={},o=i.createContext(s);function a(e){const n=i.useContext(o);return i.useMemo((function(){return"function"==typeof e?e(n):{...n,...e}}),[n,e])}function r(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(s):e.components||s:a(e.components),i.createElement(o.Provider,{value:n},e.children)}}}]); \ No newline at end of file diff --git a/assets/js/4200b1a9.d764baec.js b/assets/js/4200b1a9.d764baec.js new file mode 100644 index 0000000..e320695 --- /dev/null +++ b/assets/js/4200b1a9.d764baec.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[866],{24612: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\\n\\n1. enabling the Copr repository, and\\n2. installing the desired package.\\n\\nSo in shell you would do\\n\\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]:\\n 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>` 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\\n```rust\\npub struct ColumnIterator<\'a, T> {\\n map: &\'a [Vec],\\n column: usize,\\n\\n i: usize,\\n}\\n\\nimpl<\'a, T> ColumnIterator<\'a, T> {\\n pub fn new(map: &\'a [Vec], 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 {\\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\\n```rust\\nlet mut find_boundaries = |constructor: fn(usize) -> Orientation,\\n iterator: &mut dyn Iterator,\\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\\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\\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\\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\\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\\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\\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\\n```rust\\nfn get_bounds(positions: &Input) -> (Vector2D, Vector2D) {\\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::), f(isize::MIN, &max::))\\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\\n```rust\\n&dyn Fn(isize, isize) -> isize\\n```\\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) {} // 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`, 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) {} // 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\\n- it explains why you need to use `dyn`, but\\n- it still mentions that trait objects need to be heap-allocated via `Box`\\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`\\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`, 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\\n```rust\\nimpl Index 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\\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\\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\\n```rust\\nuse std::cmp::{Ord, Reverse};\\nuse std::collections::BinaryHeap;\\n\\npub struct MinHeap {\\n heap: BinaryHeap>,\\n}\\n\\nimpl MinHeap {\\n pub fn new() -> MinHeap {\\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 {\\n self.heap.pop().map(|Reverse(x)| x)\\n }\\n}\\n\\nimpl Default for MinHeap {\\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\\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\\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`\\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\\n```diff\\n fn parse_input>(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\\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::()).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\\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::().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.57,"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\\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\\n```rust\\nfn pairings(\\n valves: &BTreeSet,\\n) -> impl Iterator, BTreeSet)> + \'_ {\\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\\n```rust\\nfn occupied(shape: &[Vec]) -> impl Iterator + \'_ {\\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` 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\\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 {\\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>`. In the end I failed on _wrong answer_. I have also encountered\\na rather interesting issue with `.borrow_mut()` method being used on `Rc>`.\\n\\n#### `.borrow_mut()`\\n\\nConsider the following snippet of the code (taken from the documentation):\\n\\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> = 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>` 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```\\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>>`\\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>`\\n\\nLet\'s consider a variable `x` of type `Rc>`. 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` implements a `.borrow_mut()`\\nmethod. OK, but how can we call it on the `Rc`? Easily! `Rc` implements\\n`Deref` and therefore you can call methods on `Rc` 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`, \u2026:\\n>\\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`? Well, it needs\\n`&self`, so the `Deref` implements the `.borrow_mut()` for the `Rc>`.\\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\\n```rust\\nimpl BorrowMut for String\\n\\nimpl BorrowMut for &mut T\\nwhere\\n T: ?Sized,\\n\\nimpl BorrowMut for T\\nwhere\\n T: ?Sized,\\n\\nimpl BorrowMut<[T]> for Vec\\nwhere\\n A: Allocator,\\n\\nimpl BorrowMut for Box\\nwhere\\n A: Allocator,\\n T: ?Sized,\\n\\nimpl 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>` 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`:\\n\\n```rust\\n// trait\\npub trait BorrowMut: Borrow\\nwhere\\n Borrowed: ?Sized,\\n{\\n fn borrow_mut(&mut self) -> &mut Borrowed;\\n}\\n\\n// \u2039RefCell.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`.\\n\\n**In my opinion**, `RefCell` 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`.\\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> diagonalSort(vector>& 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 \\n#include \\n\\nusing matrix = std::vector>;\\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\\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\\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\\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\\n- construct the object\\n- get the beginning\\n- get the end (the \u201csentinel\u201d)\\n\\n```cpp\\ntemplate \\nclass diagonals {\\n using matrix_t = std::vector>;\\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>`, 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\\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 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\\n```cpp\\ntemplate \\nclass diagonal {\\n using matrix_t = std::vector>;\\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\\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\\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```\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1792:11: error: object of type \'diagonal::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_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_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_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_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_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::matrix_t &\' (aka \'vector> &\')\\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_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_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_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_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::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::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_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_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_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::matrix_t &\' (aka \'vector> &\')\\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```\\n/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1792:11: error: object of type \'diagonal::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::matrix_t &\' (aka \'vector> &\')\\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\\n```diff\\n# we need to keep a different type than reference\\n- matrix_t& m;\\n+ std::reference_wrapper 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>`\\n- indexing `Vec>` 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 Vector2D {\\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], idx: &Vector2D) -> &\'a U\\nwhere\\n usize: TryFrom,\\n >::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` which basically\\nsays that `usize` must implement `TryFrom` 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 `>::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\\n- `v: &\'a [Vec]` represents the 2D `Vec`, we are indexing, `Vec` implements\\n `Slice` trait and _clippy_ recommends using `&[T]` to `&Vec`, exact details\\n are unknown to me\\n- `idx: &Vector2D` 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\\n```rust\\npub fn index_mut<\'a, T, U>(v: &\'a mut [Vec], idx: &Vector2D) -> &\'a mut U\\nwhere\\n usize: TryFrom,\\n >::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`, we don\'t need to consider containers as `T`, Rust\\nimplements indexing as traits `Index` and `IndexMut` 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` that is of a relevance\\nbecause of\\n\\n```rust\\nimpl Index for [T]\\nwhere\\n I: SliceIndex<[T]>\\n\\nimpl Index for Vec\\nwhere\\n I: SliceIndex<[T]>,\\n A: Allocator\\n\\nimpl Index for [T; N]\\nwhere\\n [T]: Index\\n```\\n\\nIn other words, if your type implements `SliceIndex` 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]` or `Vec>`.\\nThis requirement could be countered by removing inner type `Vec` and constraining\\nit by a trait `Index` (or `IndexMut` respectively) in a following way\\n\\n```rust\\npub fn index<\'a, C, T>(v: &\'a [C], idx: &Vector2D) -> &\'a C::Output\\nwhere\\n usize: TryFrom,\\n >::Error: Debug,\\n T: Copy,\\n C: Index\\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\\n```rust\\npub fn in_range(v: &[Vec], idx: &Vector2D) -> bool\\nwhere\\n usize: TryInto,\\n >::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::::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` which we can use to our advantage.\\n\\n```rust\\npub fn in_range(v: &[Vec], idx: &Vector2D) -> bool\\nwhere\\n T: Copy,\\n usize: TryFrom,\\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` 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`.\\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\\n```rust\\npub fn and_then(self, op: F) -> Result\\nwhere\\n F: FnOnce(T) -> Result\\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(self, op: F) -> Result\\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\\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\\n```rust\\npub trait Solution {\\n fn parse_input>(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\\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::().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\\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\\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\\n```rust\\nuse aoc_2022::*;\\n\\ntype Input = String;\\ntype Output = String;\\n\\nstruct DayXX;\\nimpl Solution for DayXX {\\n fn parse_input>(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\\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` type that can be\\ndefined as\\n\\n```rust\\nenum Result {\\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\\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\\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\\n```rust\\nfn bfs(\\n graph: &[Vec], start: &Position, has_edge: F, is_target: G\\n) -> Option\\nwhere\\n F: Fn(&[Vec], &Position, &Position) -> bool,\\n G: Fn(&[Vec], &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\\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` 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 Index> for [C]\\nwhere\\n I: Copy + TryInto,\\n >::Error: Debug,\\n C: Index,\\n{\\n type Output = C::Output;\\n\\n fn index(&self, index: Vector2D) -> &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 IndexMut> for [C]\\nwhere\\n I: Copy + TryInto,\\n >::Error: Debug,\\n C: IndexMut,\\n{\\n fn index_mut(&mut self, index: Vector2D) -> &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: Sized {\\n type Error;\\n\\n fn try_from(value: T) -> Result;\\n}\\n\\npub trait TryInto: Sized {\\n type Error;\\n\\n fn try_into(self) -> Result;\\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]` cannot be indexed by `aoc_2022::Vector2D`\\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]>` is not implemented for `aoc_2022::Vector2D`\\n = note: required for `std::vec::Vec>` to implement `std::ops::Index>`\\n\\nerror[E0277]: the type `[std::vec::Vec]` cannot be indexed by `aoc_2022::Vector2D`\\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]>` is not implemented for `aoc_2022::Vector2D`\\n = note: required for `std::vec::Vec>` to implement `std::ops::Index>`\\n\\nerror[E0277]: the type `[std::vec::Vec]` cannot be indexed by `aoc_2022::Vector2D`\\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]>` is not implemented for `aoc_2022::Vector2D`\\n = note: required for `std::vec::Vec>` to implement `std::ops::Index>`\\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]`, but this is coming from a helper functions that\\ntake `&Vec>` instead. And\u2026 we don\'t implement `Index` and `IndexMut` for\\nthose. Just for the slices. \ud83e\udd2f _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\\n```rust\\nmacro_rules! generate_indices {\\n ($container:ty) => {\\n impl Index> for $container\\n where\\n I: Copy + TryInto,\\n >::Error: Debug,\\n C: Index,\\n {\\n type Output = C::Output;\\n\\n fn index(&self, index: Vector2D) -> &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 IndexMut> for $container\\n where\\n I: Copy + TryInto,\\n >::Error: Debug,\\n C: IndexMut,\\n {\\n fn index_mut(&mut self, index: Vector2D) -> &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\\n```rust\\ngenerate_indices!(VecDeque);\\ngenerate_indices!([C]);\\ngenerate_indices!(Vec);\\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\\n```rust\\nfn get_sum(nums: &Vec) -> 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\\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 {\\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\\n```rust\\ntype Numbers = Vec;\\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\\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\\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\\n```rust\\nlet top: HashSet = [1, 2, 3].iter().collect();\\nlet bottom: HashSet = [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\\n```rust\\nlet top: HashSet = [1, 2, 3].into_iter().collect();\\nlet bottom: HashSet = [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\\n```rust\\nprintln!(\\"Common elements: {:?}\\", top.intersection(&bottom));\\n```\\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\\n```rust\\npub fn intersection<\'a>(\\n\xa0\xa0\xa0\xa0&\'a self,\\n\xa0\xa0\xa0\xa0other: &\'a HashSet\\n) -> Intersection<\'a, T, S>\\n```\\n\\nOK\u2026 Huh\u2026 But we have an example there!\\n\\n```rust\\nlet intersection: HashSet<_> = a.intersection(&b).collect();\\n```\\n\\nCool, that\'s all we need.\\n\\n```rust\\nlet top: HashSet = [1, 2, 3, 4].into_iter().collect();\\nlet bottom: HashSet = [3, 4, 5, 6].into_iter().collect();\\nlet top_2: HashSet = [2, 3, 4, 5, 6].into_iter().collect();\\nlet bottom_2: HashSet = [4, 5, 6].into_iter().collect();\\n\\nlet intersection: HashSet<_> = top.intersection(&bottom).collect();\\nprintln!(\\"Intersection: {:?}\\", intersection);\\n```\\n\\n```\\nIntersection: {3, 4}\\n```\\n\\nCool, so let\'s do the intersection with the `top_2`:\\n\\n```rust\\nlet top: HashSet = [1, 2, 3, 4].into_iter().collect();\\nlet bottom: HashSet = [3, 4, 5, 6].into_iter().collect();\\nlet top_2: HashSet = [2, 3, 4, 5, 6].into_iter().collect();\\nlet bottom_2: HashSet = [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\\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`\\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\\n```rust\\nlet top: HashSet = [1, 2, 3, 4].into_iter().collect();\\nlet bottom: HashSet = [3, 4, 5, 6].into_iter().collect();\\nlet top_2: HashSet = [2, 3, 4, 5, 6].into_iter().collect();\\nlet bottom_2: HashSet = [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\\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```\\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:::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\\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```\\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` 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>`. And I got my _ass whopped_ by the compiler once again. /o\\\\\\n\\n:::tip\\n\\n`Box` represents a dynamically allocated memory on heap. It is a single pointer,\\nyou can imagine this as `std::unique_ptr` in C++.\\n\\n`Rc` 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` in C++.\\n\\nNow the fun stuff. Neither of them lets you **mutate** the contents of the memory.\\n\\n`Cell` 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` is similar to the `Cell`, 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` in Rust, you want\\nto have `Rc>`.\\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\\n```rust\\ntype FileHandle = Rc>;\\n\\n#[derive(Debug)]\\nenum AocFile {\\n File(usize),\\n Directory(BTreeMap),\\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\\n- `File(usize)`, e.g. `AocFile::File(123)` and we can pattern match it, if we\\n need to\\n- `Directory(BTreeMap)` 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` vs `Rc>`\\n\\nIt has been brought up that I have a contradicting statement regarding the\\ndynamically allocated memory. Specifically:\\n\\n- You can imagine `Rc` as an `std::shared_ptr` (in C++)\\n- When you want an equivalent of `std::shared_ptr`, you want to use\\n `Rc>`\\n\\nNow, in Rust it is a bit more complicated, because the type that represents the\\n\u201cshared pointer\u201d is `Rc`. What `RefCell` 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`).\\n\\nTherefore to be precise and correct about the equivalents of `std::shared_ptr`\\nin Rust, we can say that\\n\\n- `Rc` is an equivalent of a `const std::shared_ptr`,\\n- and `Rc>` is an equivalent of a `std::shared_ptr`.\\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`)\\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\\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\\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\\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\\n```rust\\n/// Reads file to the string.\\npub fn file_to_string>(pathname: P) -> String;\\n\\n/// Reads file and returns it as a vector of characters.\\npub fn file_to_chars>(pathname: P) -> Vec;\\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, T: FromStr>(pathname: P) -> Vec\\nwhere\\n ::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(\\n iter: impl Iterator\\n) -> Vec\\nwhere\\n ::Err: std::fmt::Debug,\\n U: Deref;\\n\\n/// Reads file and returns it as a vector of its lines.\\npub fn file_to_lines>(pathname: P) -> Vec;\\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\\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\\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\\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\\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\\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\\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```\\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\\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]:\\n Copy-pasting might be a relaxing thing to do, but you can also discover\\n nasty stuff about your PC. See [this Reddit post and the comment].\\n\\n[^2]: [GitHub profile](https://github.com/martinjonas)\\n[^3]:\\n Even though you can use it even for libraries, but handling errors from\\n libraries 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"}]}')}}]); \ No newline at end of file diff --git a/assets/js/4200b1a9.faadd2c9.js b/assets/js/4200b1a9.faadd2c9.js deleted file mode 100644 index 10dc5bd..0000000 --- a/assets/js/4200b1a9.faadd2c9.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[866],{24612: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>` 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],\\n column: usize,\\n\\n i: usize,\\n}\\n\\nimpl<\'a, T> ColumnIterator<\'a, T> {\\n pub fn new(map: &\'a [Vec], 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 {\\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,\\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, Vector2D) {\\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::), f(isize::MIN, &max::))\\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) {} // 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`, 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) {} // 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`\\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`\\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`, 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 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 {\\n heap: BinaryHeap>,\\n}\\n\\nimpl MinHeap {\\n pub fn new() -> MinHeap {\\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 {\\n self.heap.pop().map(|Reverse(x)| x)\\n }\\n}\\n\\nimpl Default for MinHeap {\\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`\\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>(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::()).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::().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,\\n) -> impl Iterator, BTreeSet)> + \'_ {\\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]) -> impl Iterator + \'_ {\\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` 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 {\\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>`. In the end I failed on _wrong answer_. I have also encountered\\na rather interesting issue with `.borrow_mut()` method being used on `Rc>`.\\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> = 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>` 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>>`\\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>`\\n\\nLet\'s consider a variable `x` of type `Rc>`. 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` implements a `.borrow_mut()`\\nmethod. OK, but how can we call it on the `Rc`? Easily! `Rc` implements\\n`Deref` and therefore you can call methods on `Rc` 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`, \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`? Well, it needs\\n`&self`, so the `Deref` implements the `.borrow_mut()` for the `Rc>`.\\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 for String\\n\\nimpl BorrowMut for &mut T\\nwhere\\n T: ?Sized,\\n\\nimpl BorrowMut for T\\nwhere\\n T: ?Sized,\\n\\nimpl BorrowMut<[T]> for Vec\\nwhere\\n A: Allocator,\\n\\nimpl BorrowMut for Box\\nwhere\\n A: Allocator,\\n T: ?Sized,\\n\\nimpl 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>` 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`:\\n```rust\\n// trait\\npub trait BorrowMut: Borrow\\nwhere\\n Borrowed: ?Sized,\\n{\\n fn borrow_mut(&mut self) -> &mut Borrowed;\\n}\\n\\n// \u2039RefCell.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`.\\n\\n**In my opinion**, `RefCell` 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`.\\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> diagonalSort(vector>& 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 \\n#include \\n\\nusing matrix = std::vector>;\\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 \\nclass diagonals {\\n using matrix_t = std::vector>;\\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>`, 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 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 \\nclass diagonal {\\n using matrix_t = std::vector>;\\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::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_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_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_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_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_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::matrix_t &\' (aka \'vector> &\')\\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_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_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_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_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::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::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_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_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_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::matrix_t &\' (aka \'vector> &\')\\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::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::matrix_t &\' (aka \'vector> &\')\\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 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>`\\n- indexing `Vec>` 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 Vector2D {\\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], idx: &Vector2D) -> &\'a U\\nwhere\\n usize: TryFrom,\\n >::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` which basically\\nsays that `usize` must implement `TryFrom` 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 `>::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]` represents the 2D `Vec`, we are indexing, `Vec` implements\\n `Slice` trait and _clippy_ recommends using `&[T]` to `&Vec`, exact details\\n are unknown to me\\n- `idx: &Vector2D` 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], idx: &Vector2D) -> &\'a mut U\\nwhere\\n usize: TryFrom,\\n >::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`, we don\'t need to consider containers as `T`, Rust\\nimplements indexing as traits `Index` and `IndexMut` 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` that is of a relevance\\nbecause of\\n```rust\\nimpl Index for [T]\\nwhere\\n I: SliceIndex<[T]>\\n\\nimpl Index for Vec\\nwhere\\n I: SliceIndex<[T]>,\\n A: Allocator\\n\\nimpl Index for [T; N]\\nwhere\\n [T]: Index\\n```\\n\\nIn other words, if your type implements `SliceIndex` 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]` or `Vec>`.\\nThis requirement could be countered by removing inner type `Vec` 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) -> &\'a C::Output\\nwhere\\n usize: TryFrom,\\n >::Error: Debug,\\n T: Copy,\\n C: Index\\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(v: &[Vec], idx: &Vector2D) -> bool\\nwhere\\n usize: TryInto,\\n >::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::::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` which we can use to our advantage.\\n```rust\\npub fn in_range(v: &[Vec], idx: &Vector2D) -> bool\\nwhere\\n T: Copy,\\n usize: TryFrom,\\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` 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`.\\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(self, op: F) -> Result\\nwhere\\n F: FnOnce(T) -> Result\\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(self, op: F) -> Result\\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 {\\n fn parse_input>(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::().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 for DayXX {\\n fn parse_input>(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` type that can be\\ndefined as\\n```rust\\nenum Result {\\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(\\n graph: &[Vec], start: &Position, has_edge: F, is_target: G\\n) -> Option\\nwhere\\n F: Fn(&[Vec], &Position, &Position) -> bool,\\n G: Fn(&[Vec], &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` 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 Index> for [C]\\nwhere\\n I: Copy + TryInto,\\n >::Error: Debug,\\n C: Index,\\n{\\n type Output = C::Output;\\n\\n fn index(&self, index: Vector2D) -> &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 IndexMut> for [C]\\nwhere\\n I: Copy + TryInto,\\n >::Error: Debug,\\n C: IndexMut,\\n{\\n fn index_mut(&mut self, index: Vector2D) -> &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: Sized {\\n type Error;\\n\\n fn try_from(value: T) -> Result;\\n}\\n\\npub trait TryInto: Sized {\\n type Error;\\n\\n fn try_into(self) -> Result;\\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]` cannot be indexed by `aoc_2022::Vector2D`\\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]>` is not implemented for `aoc_2022::Vector2D`\\n = note: required for `std::vec::Vec>` to implement `std::ops::Index>`\\n\\nerror[E0277]: the type `[std::vec::Vec]` cannot be indexed by `aoc_2022::Vector2D`\\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]>` is not implemented for `aoc_2022::Vector2D`\\n = note: required for `std::vec::Vec>` to implement `std::ops::Index>`\\n\\nerror[E0277]: the type `[std::vec::Vec]` cannot be indexed by `aoc_2022::Vector2D`\\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]>` is not implemented for `aoc_2022::Vector2D`\\n = note: required for `std::vec::Vec>` to implement `std::ops::Index>`\\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]`, but this is coming from a helper functions that\\ntake `&Vec>` 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 Index> for $container\\n where\\n I: Copy + TryInto,\\n >::Error: Debug,\\n C: Index,\\n {\\n type Output = C::Output;\\n\\n fn index(&self, index: Vector2D) -> &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 IndexMut> for $container\\n where\\n I: Copy + TryInto,\\n >::Error: Debug,\\n C: IndexMut,\\n {\\n fn index_mut(&mut self, index: Vector2D) -> &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);\\ngenerate_indices!([C]);\\ngenerate_indices!(Vec);\\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 {\\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 {\\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;\\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 = [1, 2, 3].iter().collect();\\nlet bottom: HashSet = [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 = [1, 2, 3].into_iter().collect();\\nlet bottom: HashSet = [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\\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 = [1, 2, 3, 4].into_iter().collect();\\nlet bottom: HashSet = [3, 4, 5, 6].into_iter().collect();\\nlet top_2: HashSet = [2, 3, 4, 5, 6].into_iter().collect();\\nlet bottom_2: HashSet = [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 = [1, 2, 3, 4].into_iter().collect();\\nlet bottom: HashSet = [3, 4, 5, 6].into_iter().collect();\\nlet top_2: HashSet = [2, 3, 4, 5, 6].into_iter().collect();\\nlet bottom_2: HashSet = [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`\\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 = [1, 2, 3, 4].into_iter().collect();\\nlet bottom: HashSet = [3, 4, 5, 6].into_iter().collect();\\nlet top_2: HashSet = [2, 3, 4, 5, 6].into_iter().collect();\\nlet bottom_2: HashSet = [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` 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>`. And I got my _ass whopped_ by the compiler once again. /o\\\\\\n\\n:::tip\\n\\n`Box` represents a dynamically allocated memory on heap. It is a single pointer,\\nyou can imagine this as `std::unique_ptr` in C++.\\n\\n`Rc` 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` in C++.\\n\\nNow the fun stuff. Neither of them lets you **mutate** the contents of the memory.\\n\\n`Cell` 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` is similar to the `Cell`, 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` in Rust, you want\\nto have `Rc>`.\\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>;\\n\\n#[derive(Debug)]\\nenum AocFile {\\n File(usize),\\n Directory(BTreeMap),\\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)` 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` vs `Rc>`\\n\\nIt has been brought up that I have a contradicting statement regarding the\\ndynamically allocated memory. Specifically:\\n\\n- You can imagine `Rc` as an `std::shared_ptr` (in C++)\\n- When you want an equivalent of `std::shared_ptr`, you want to use\\n `Rc>`\\n\\nNow, in Rust it is a bit more complicated, because the type that represents the\\n\u201cshared pointer\u201d is `Rc`. What `RefCell` 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`).\\n\\nTherefore to be precise and correct about the equivalents of `std::shared_ptr`\\nin Rust, we can say that\\n\\n- `Rc` is an equivalent of a `const std::shared_ptr`,\\n- and `Rc>` is an equivalent of a `std::shared_ptr`.\\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`)\\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>(pathname: P) -> String;\\n\\n/// Reads file and returns it as a vector of characters.\\npub fn file_to_chars>(pathname: P) -> Vec;\\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, T: FromStr>(pathname: P) -> Vec\\nwhere\\n ::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(\\n iter: impl Iterator\\n) -> Vec\\nwhere\\n ::Err: std::fmt::Debug,\\n U: Deref;\\n\\n/// Reads file and returns it as a vector of its lines.\\npub fn file_to_lines>(pathname: P) -> Vec;\\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"}]}')}}]); \ No newline at end of file diff --git a/assets/js/595c7293.6c273bef.js b/assets/js/595c7293.6ef41b13.js similarity index 98% rename from assets/js/595c7293.6c273bef.js rename to assets/js/595c7293.6ef41b13.js index 497ea2d..90ff738 100644 --- a/assets/js/595c7293.6c273bef.js +++ b/assets/js/595c7293.6ef41b13.js @@ -1 +1 @@ -"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[5634],{58396:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>a,contentTitle:()=>o,default:()=>h,frontMatter:()=>r,metadata:()=>c,toc:()=>l});var i=t(85893),s=t(11151);const r={id:"seminar-08",title:"8th seminar",description:"Manipulating with files only char-by-char and a magic tree.\n"},o="8th seminar bonus assignment",c={id:"bonuses/seminar-08",title:"8th seminar",description:"Manipulating with files only char-by-char and a magic tree.\n",source:"@site/c/bonuses/08.md",sourceDirName:"bonuses",slug:"/bonuses/seminar-08",permalink:"/c/bonuses/seminar-08",draft:!1,unlisted:!1,editUrl:"https://github.com/mfocko/blog/tree/main/c/bonuses/08.md",tags:[],version:"current",lastUpdatedAt:1704291155,formattedLastUpdatedAt:"Jan 3, 2024",frontMatter:{id:"seminar-08",title:"8th seminar",description:"Manipulating with files only char-by-char and a magic tree.\n"},sidebar:"autogeneratedBar",previous:{title:"5th and 6th seminar",permalink:"/c/bonuses/seminar-05-06"},next:{title:"10th seminar",permalink:"/c/bonuses/seminar-10"}},a={},l=[{value:"Introduction",id:"introduction",level:2},{value:"Warning",id:"warning",level:2},{value:"Testing",id:"testing",level:2},{value:"Task no. 1: Counting (0.75 K\u20a1)",id:"task-no-1-counting-075-k",level:2},{value:"Requirements",id:"requirements",level:3},{value:"Bonus part (0.75 K\u20a1)",id:"bonus-part-075-k",level:3},{value:"Task no. 2: Weird trees (1 K\u20a1)",id:"task-no-2-weird-trees-1-k",level:2},{value:"Submitting",id:"submitting",level:2}];function d(e){const n={a:"a",blockquote:"blockquote",code:"code",em:"em",h1:"h1",h2:"h2",h3:"h3",hr:"hr",img:"img",li:"li",ol:"ol",p:"p",pre:"pre",strong:"strong",ul:"ul",...(0,s.a)(),...e.components};return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(n.h1,{id:"8th-seminar-bonus-assignment",children:"8th seminar bonus assignment"}),"\n",(0,i.jsx)(n.p,{children:(0,i.jsx)(n.a,{href:"pathname:///files/c/bonuses/08.tar.gz",children:"Source"})}),"\n",(0,i.jsx)(n.h2,{id:"introduction",children:"Introduction"}),"\n",(0,i.jsx)(n.p,{children:"In this bonus you can implement two tasks, one of them has a bonus part with generic\nsolution."}),"\n",(0,i.jsx)(n.p,{children:"One is focused on counting ananas or in case of generic version any substring in\nthe file, but with a restriction on the function you use."}),"\n",(0,i.jsx)(n.p,{children:"Other one has a more algorithmic spirit."}),"\n",(0,i.jsx)(n.p,{children:"For this bonus you can get at maximum 2.5 K\u20a1."}),"\n",(0,i.jsx)(n.h2,{id:"warning",children:"Warning"}),"\n",(0,i.jsxs)(n.p,{children:[(0,i.jsx)(n.strong,{children:"DO NOT COMMIT test data"})," to your own git repository, since the tests include\nfiles that exceed 10MB by themselves. Even if they are on separate branch, they\ntake up the space."]}),"\n",(0,i.jsx)(n.h2,{id:"testing",children:"Testing"}),"\n",(0,i.jsxs)(n.p,{children:["For testing you are provided with python script (requires ",(0,i.jsx)(n.code,{children:"click"})," to be installed:\n",(0,i.jsx)(n.code,{children:"pip3 install --user click"}),") and ",(0,i.jsx)(n.code,{children:"Makefile"})," that provides following targets:"]}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"check-counting"})," - runs the ",(0,i.jsx)(n.code,{children:"counting"})," tests"]}),"\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"check-counting-bonus"})," - runs the ",(0,i.jsx)(n.code,{children:"counting"})," tests with bonus implemented"]}),"\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"check"})," - runs both ",(0,i.jsx)(n.code,{children:"counting"})," and ",(0,i.jsx)(n.code,{children:"counting-bonus"})," tests"]}),"\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"clean"})," - removes output files from the test runs"]}),"\n"]}),"\n",(0,i.jsx)(n.h2,{id:"task-no-1-counting-075-k",children:"Task no. 1: Counting (0.75 K\u20a1)"}),"\n",(0,i.jsx)(n.p,{children:"Your first task is to make smallish program that counts occurences of specific\n(or given) word from file and writes the number to other file."}),"\n",(0,i.jsx)(n.p,{children:"Usage of the program is:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{children:"Usage: ./counting [string-to-be-counted]\n"})}),"\n",(0,i.jsx)(n.p,{children:"Arguments that are passed to the program represent:"}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:""})," - path to the file where we count the words"]}),"\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:""})," - path to the file where we output the count"]}),"\n",(0,i.jsxs)(n.li,{children:["(optional argument) ",(0,i.jsx)(n.code,{children:"[string-to-be-counted]"})," - in case you implement bonus,\notherwise we default to word ",(0,i.jsx)(n.code,{children:"ananas"})," ;)"]}),"\n"]}),"\n",(0,i.jsx)(n.p,{children:"In skeleton you are given 3 empty, but documented, functions to implement."}),"\n",(0,i.jsxs)(n.ol,{children:["\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"count_anything"})," - function accepts input file and substring to be counted in\nthe file, returns the count."]}),"\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"count_ananas"})," - same as ",(0,i.jsx)(n.code,{children:"count_anything"}),", but specialized for ananases, the\ndefault implementation from the skeleton expects you to implement ",(0,i.jsx)(n.code,{children:"count_anything"}),"\nand therefore it just calls the other function."]}),"\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"write_number"})," - function that writes the number to the file, why would you\nneed the function is explained later :)"]}),"\n"]}),"\n",(0,i.jsx)(n.h3,{id:"requirements",children:"Requirements"}),"\n",(0,i.jsxs)(n.p,{children:["For manipulation with the files you are only allowed to use ",(0,i.jsx)(n.code,{children:"fopen"}),", ",(0,i.jsx)(n.code,{children:"fclose"}),",\n",(0,i.jsx)(n.code,{children:"fgetc"})," and ",(0,i.jsx)(n.code,{children:"fputc"}),". Functions like ",(0,i.jsx)(n.code,{children:"fprintf"})," (except for ",(0,i.jsx)(n.code,{children:"stderr"})," or logging) and\n",(0,i.jsx)(n.code,{children:"fscanf"})," are ",(0,i.jsx)(n.strong,{children:"forbidden"}),"."]}),"\n",(0,i.jsx)(n.p,{children:"In case you struggle and want to use one of those functions, the solution will be\npenalized by 50% of points."}),"\n",(0,i.jsx)(n.h3,{id:"bonus-part-075-k",children:"Bonus part (0.75 K\u20a1)"}),"\n",(0,i.jsxs)(n.p,{children:["Bonus part of this assignment is to implement ",(0,i.jsx)(n.code,{children:"count_anything"})," rather than ",(0,i.jsx)(n.code,{children:"count_ananas"}),"."]}),"\n",(0,i.jsxs)(n.blockquote,{children:["\n",(0,i.jsx)(n.p,{children:"Smaller hint: This task does not need dynamic allocation :) You just need one\ngood helper function and the right idea ;)"}),"\n"]}),"\n",(0,i.jsx)(n.h2,{id:"task-no-2-weird-trees-1-k",children:"Task no. 2: Weird trees (1 K\u20a1)"}),"\n",(0,i.jsxs)(n.p,{children:["In this task we are crossing our paths with ",(0,i.jsx)(n.em,{children:"algorithms and data structures"}),".\nYour task is to write a program that constructs tree from the file that is given\nas an argument and pretty-prints it."]}),"\n",(0,i.jsxs)(n.p,{children:["Input file consists of lines, that include ",(0,i.jsx)(n.code,{children:"key"})," and ",(0,i.jsx)(n.code,{children:"rank"})," in form ",(0,i.jsx)(n.code,{children:"key;rank"}),"\nor ",(0,i.jsx)(n.code,{children:"nil"}),". Why would we have ",(0,i.jsx)(n.code,{children:"nil"})," in a file? The file represents pre-order iteration\nthrough the tree. Leaves never have rank different than 0, so you can safely assume\n2 non-existing ",(0,i.jsx)(n.code,{children:"nil"}),"s in the input after you read such node ;)"]}),"\n",(0,i.jsxs)("table",{children:[(0,i.jsxs)("tr",{children:[(0,i.jsx)("th",{children:"Example input file"}),(0,i.jsx)("th",{children:"Tree it represents"})]}),(0,i.jsxs)("tr",{children:[(0,i.jsx)("td",{children:(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{children:"8;4\n5;3\n3;2\n2;1\n1;0\nnil\n4;0\n7;1\n6;0\nnil\n11;2\n10;1\n9;0\nnil\n12;0\n"})})}),(0,i.jsx)("td",{children:(0,i.jsx)(n.p,{children:(0,i.jsx)(n.img,{alt:"tree",src:t(30073).Z+"",width:"633",height:"684"})})})]})]}),"\n",(0,i.jsxs)(n.p,{children:["In this task you are only provided with different trees in the ",(0,i.jsx)(n.code,{children:"test-trees"})," directory.\nImplementation and format of the pretty-print is totally up to you. :)"]}),"\n",(0,i.jsx)(n.p,{children:"Example of mine for the tree above:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{children:"8 (rank = 4)\n+-- 5 (rank = 3)\n| +-- 3 (rank = 2)\n| | +-- 2 (rank = 1)\n| | | +-- 1 (rank = 0)\n| | +-- 4 (rank = 0)\n| +-- 7 (rank = 1)\n| +-- 6 (rank = 0)\n+-- 11 (rank = 2)\n +-- 10 (rank = 1)\n | +-- 9 (rank = 0)\n +-- 12 (rank = 0)\n"})}),"\n",(0,i.jsxs)(n.blockquote,{children:["\n",(0,i.jsx)(n.p,{children:"Can you find out what are those trees? :)"}),"\n"]}),"\n",(0,i.jsx)(n.h2,{id:"submitting",children:"Submitting"}),"\n",(0,i.jsx)(n.p,{children:"In case you have any questions, feel free to reach out to me."}),"\n",(0,i.jsx)(n.hr,{})]})}function h(e={}){const{wrapper:n}={...(0,s.a)(),...e.components};return n?(0,i.jsx)(n,{...e,children:(0,i.jsx)(d,{...e})}):d(e)}},30073:(e,n,t)=>{t.d(n,{Z:()=>i});const i=t.p+"assets/images/tree-c9e37f87f9095c00fad33ea034485ce6.png"},11151:(e,n,t)=>{t.d(n,{Z:()=>c,a:()=>o});var i=t(67294);const s={},r=i.createContext(s);function o(e){const n=i.useContext(r);return i.useMemo((function(){return"function"==typeof e?e(n):{...n,...e}}),[n,e])}function c(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(s):e.components||s:o(e.components),i.createElement(r.Provider,{value:n},e.children)}}}]); \ No newline at end of file +"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[5634],{58396:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>a,contentTitle:()=>o,default:()=>h,frontMatter:()=>r,metadata:()=>c,toc:()=>l});var i=t(85893),s=t(11151);const r={id:"seminar-08",title:"8th seminar",description:"Manipulating with files only char-by-char and a magic tree.\n"},o="8th seminar bonus assignment",c={id:"bonuses/seminar-08",title:"8th seminar",description:"Manipulating with files only char-by-char and a magic tree.\n",source:"@site/c/bonuses/08.md",sourceDirName:"bonuses",slug:"/bonuses/seminar-08",permalink:"/c/bonuses/seminar-08",draft:!1,unlisted:!1,editUrl:"https://github.com/mfocko/blog/tree/main/c/bonuses/08.md",tags:[],version:"current",lastUpdatedAt:1704558496,formattedLastUpdatedAt:"Jan 6, 2024",frontMatter:{id:"seminar-08",title:"8th seminar",description:"Manipulating with files only char-by-char and a magic tree.\n"},sidebar:"autogeneratedBar",previous:{title:"5th and 6th seminar",permalink:"/c/bonuses/seminar-05-06"},next:{title:"10th seminar",permalink:"/c/bonuses/seminar-10"}},a={},l=[{value:"Introduction",id:"introduction",level:2},{value:"Warning",id:"warning",level:2},{value:"Testing",id:"testing",level:2},{value:"Task no. 1: Counting (0.75 K\u20a1)",id:"task-no-1-counting-075-k",level:2},{value:"Requirements",id:"requirements",level:3},{value:"Bonus part (0.75 K\u20a1)",id:"bonus-part-075-k",level:3},{value:"Task no. 2: Weird trees (1 K\u20a1)",id:"task-no-2-weird-trees-1-k",level:2},{value:"Submitting",id:"submitting",level:2}];function d(e){const n={a:"a",blockquote:"blockquote",code:"code",em:"em",h1:"h1",h2:"h2",h3:"h3",hr:"hr",img:"img",li:"li",ol:"ol",p:"p",pre:"pre",strong:"strong",ul:"ul",...(0,s.a)(),...e.components};return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(n.h1,{id:"8th-seminar-bonus-assignment",children:"8th seminar bonus assignment"}),"\n",(0,i.jsx)(n.p,{children:(0,i.jsx)(n.a,{href:"pathname:///files/c/bonuses/08.tar.gz",children:"Source"})}),"\n",(0,i.jsx)(n.h2,{id:"introduction",children:"Introduction"}),"\n",(0,i.jsx)(n.p,{children:"In this bonus you can implement two tasks, one of them has a bonus part with generic\nsolution."}),"\n",(0,i.jsx)(n.p,{children:"One is focused on counting ananas or in case of generic version any substring in\nthe file, but with a restriction on the function you use."}),"\n",(0,i.jsx)(n.p,{children:"Other one has a more algorithmic spirit."}),"\n",(0,i.jsx)(n.p,{children:"For this bonus you can get at maximum 2.5 K\u20a1."}),"\n",(0,i.jsx)(n.h2,{id:"warning",children:"Warning"}),"\n",(0,i.jsxs)(n.p,{children:[(0,i.jsx)(n.strong,{children:"DO NOT COMMIT test data"})," to your own git repository, since the tests include\nfiles that exceed 10MB by themselves. Even if they are on separate branch, they\ntake up the space."]}),"\n",(0,i.jsx)(n.h2,{id:"testing",children:"Testing"}),"\n",(0,i.jsxs)(n.p,{children:["For testing you are provided with python script (requires ",(0,i.jsx)(n.code,{children:"click"})," to be installed:\n",(0,i.jsx)(n.code,{children:"pip3 install --user click"}),") and ",(0,i.jsx)(n.code,{children:"Makefile"})," that provides following targets:"]}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"check-counting"})," - runs the ",(0,i.jsx)(n.code,{children:"counting"})," tests"]}),"\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"check-counting-bonus"})," - runs the ",(0,i.jsx)(n.code,{children:"counting"})," tests with bonus implemented"]}),"\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"check"})," - runs both ",(0,i.jsx)(n.code,{children:"counting"})," and ",(0,i.jsx)(n.code,{children:"counting-bonus"})," tests"]}),"\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"clean"})," - removes output files from the test runs"]}),"\n"]}),"\n",(0,i.jsx)(n.h2,{id:"task-no-1-counting-075-k",children:"Task no. 1: Counting (0.75 K\u20a1)"}),"\n",(0,i.jsx)(n.p,{children:"Your first task is to make smallish program that counts occurences of specific\n(or given) word from file and writes the number to other file."}),"\n",(0,i.jsx)(n.p,{children:"Usage of the program is:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{children:"Usage: ./counting [string-to-be-counted]\n"})}),"\n",(0,i.jsx)(n.p,{children:"Arguments that are passed to the program represent:"}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:""})," - path to the file where we count the words"]}),"\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:""})," - path to the file where we output the count"]}),"\n",(0,i.jsxs)(n.li,{children:["(optional argument) ",(0,i.jsx)(n.code,{children:"[string-to-be-counted]"})," - in case you implement bonus,\notherwise we default to word ",(0,i.jsx)(n.code,{children:"ananas"})," ;)"]}),"\n"]}),"\n",(0,i.jsx)(n.p,{children:"In skeleton you are given 3 empty, but documented, functions to implement."}),"\n",(0,i.jsxs)(n.ol,{children:["\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"count_anything"})," - function accepts input file and substring to be counted in\nthe file, returns the count."]}),"\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"count_ananas"})," - same as ",(0,i.jsx)(n.code,{children:"count_anything"}),", but specialized for ananases, the\ndefault implementation from the skeleton expects you to implement ",(0,i.jsx)(n.code,{children:"count_anything"}),"\nand therefore it just calls the other function."]}),"\n",(0,i.jsxs)(n.li,{children:[(0,i.jsx)(n.code,{children:"write_number"})," - function that writes the number to the file, why would you\nneed the function is explained later :)"]}),"\n"]}),"\n",(0,i.jsx)(n.h3,{id:"requirements",children:"Requirements"}),"\n",(0,i.jsxs)(n.p,{children:["For manipulation with the files you are only allowed to use ",(0,i.jsx)(n.code,{children:"fopen"}),", ",(0,i.jsx)(n.code,{children:"fclose"}),",\n",(0,i.jsx)(n.code,{children:"fgetc"})," and ",(0,i.jsx)(n.code,{children:"fputc"}),". Functions like ",(0,i.jsx)(n.code,{children:"fprintf"})," (except for ",(0,i.jsx)(n.code,{children:"stderr"})," or logging) and\n",(0,i.jsx)(n.code,{children:"fscanf"})," are ",(0,i.jsx)(n.strong,{children:"forbidden"}),"."]}),"\n",(0,i.jsx)(n.p,{children:"In case you struggle and want to use one of those functions, the solution will be\npenalized by 50% of points."}),"\n",(0,i.jsx)(n.h3,{id:"bonus-part-075-k",children:"Bonus part (0.75 K\u20a1)"}),"\n",(0,i.jsxs)(n.p,{children:["Bonus part of this assignment is to implement ",(0,i.jsx)(n.code,{children:"count_anything"})," rather than ",(0,i.jsx)(n.code,{children:"count_ananas"}),"."]}),"\n",(0,i.jsxs)(n.blockquote,{children:["\n",(0,i.jsx)(n.p,{children:"Smaller hint: This task does not need dynamic allocation :) You just need one\ngood helper function and the right idea ;)"}),"\n"]}),"\n",(0,i.jsx)(n.h2,{id:"task-no-2-weird-trees-1-k",children:"Task no. 2: Weird trees (1 K\u20a1)"}),"\n",(0,i.jsxs)(n.p,{children:["In this task we are crossing our paths with ",(0,i.jsx)(n.em,{children:"algorithms and data structures"}),".\nYour task is to write a program that constructs tree from the file that is given\nas an argument and pretty-prints it."]}),"\n",(0,i.jsxs)(n.p,{children:["Input file consists of lines, that include ",(0,i.jsx)(n.code,{children:"key"})," and ",(0,i.jsx)(n.code,{children:"rank"})," in form ",(0,i.jsx)(n.code,{children:"key;rank"}),"\nor ",(0,i.jsx)(n.code,{children:"nil"}),". Why would we have ",(0,i.jsx)(n.code,{children:"nil"})," in a file? The file represents pre-order iteration\nthrough the tree. Leaves never have rank different than 0, so you can safely assume\n2 non-existing ",(0,i.jsx)(n.code,{children:"nil"}),"s in the input after you read such node ;)"]}),"\n",(0,i.jsxs)("table",{children:[(0,i.jsxs)("tr",{children:[(0,i.jsx)("th",{children:"Example input file"}),(0,i.jsx)("th",{children:"Tree it represents"})]}),(0,i.jsxs)("tr",{children:[(0,i.jsx)("td",{children:(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{children:"8;4\n5;3\n3;2\n2;1\n1;0\nnil\n4;0\n7;1\n6;0\nnil\n11;2\n10;1\n9;0\nnil\n12;0\n"})})}),(0,i.jsx)("td",{children:(0,i.jsx)(n.p,{children:(0,i.jsx)(n.img,{alt:"tree",src:t(30073).Z+"",width:"633",height:"684"})})})]})]}),"\n",(0,i.jsxs)(n.p,{children:["In this task you are only provided with different trees in the ",(0,i.jsx)(n.code,{children:"test-trees"})," directory.\nImplementation and format of the pretty-print is totally up to you. :)"]}),"\n",(0,i.jsx)(n.p,{children:"Example of mine for the tree above:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{children:"8 (rank = 4)\n+-- 5 (rank = 3)\n| +-- 3 (rank = 2)\n| | +-- 2 (rank = 1)\n| | | +-- 1 (rank = 0)\n| | +-- 4 (rank = 0)\n| +-- 7 (rank = 1)\n| +-- 6 (rank = 0)\n+-- 11 (rank = 2)\n +-- 10 (rank = 1)\n | +-- 9 (rank = 0)\n +-- 12 (rank = 0)\n"})}),"\n",(0,i.jsxs)(n.blockquote,{children:["\n",(0,i.jsx)(n.p,{children:"Can you find out what are those trees? :)"}),"\n"]}),"\n",(0,i.jsx)(n.h2,{id:"submitting",children:"Submitting"}),"\n",(0,i.jsx)(n.p,{children:"In case you have any questions, feel free to reach out to me."}),"\n",(0,i.jsx)(n.hr,{})]})}function h(e={}){const{wrapper:n}={...(0,s.a)(),...e.components};return n?(0,i.jsx)(n,{...e,children:(0,i.jsx)(d,{...e})}):d(e)}},30073:(e,n,t)=>{t.d(n,{Z:()=>i});const i=t.p+"assets/images/tree-c9e37f87f9095c00fad33ea034485ce6.png"},11151:(e,n,t)=>{t.d(n,{Z:()=>c,a:()=>o});var i=t(67294);const s={},r=i.createContext(s);function o(e){const n=i.useContext(r);return i.useMemo((function(){return"function"==typeof e?e(n):{...n,...e}}),[n,e])}function c(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(s):e.components||s:o(e.components),i.createElement(r.Provider,{value:n},e.children)}}}]); \ No newline at end of file diff --git a/assets/js/7052c0bc.54d577f1.js b/assets/js/7052c0bc.acb5879a.js similarity index 90% rename from assets/js/7052c0bc.54d577f1.js rename to assets/js/7052c0bc.acb5879a.js index f5608aa..7c46b85 100644 --- a/assets/js/7052c0bc.54d577f1.js +++ b/assets/js/7052c0bc.acb5879a.js @@ -1 +1 @@ -"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[9731],{42286:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>s,contentTitle:()=>c,default:()=>d,frontMatter:()=>i,metadata:()=>a,toc:()=>p});var o=n(85893),r=n(11151);const i={id:"cpp-intro",title:"Introduction",slug:"/"},c=void 0,a={id:"cpp-intro",title:"Introduction",description:"",source:"@site/cpp/00-intro.md",sourceDirName:".",slug:"/",permalink:"/cpp/",draft:!1,unlisted:!1,editUrl:"https://github.com/mfocko/blog/tree/main/cpp/00-intro.md",tags:[],version:"current",lastUpdatedAt:1704291155,formattedLastUpdatedAt:"Jan 3, 2024",sidebarPosition:0,frontMatter:{id:"cpp-intro",title:"Introduction",slug:"/"},sidebar:"autogeneratedBar",next:{title:"Exceptions and RAII",permalink:"/cpp/category/exceptions-and-raii"}},s={},p=[];function u(t){return(0,o.jsx)(o.Fragment,{})}function d(t={}){const{wrapper:e}={...(0,r.a)(),...t.components};return e?(0,o.jsx)(e,{...t,children:(0,o.jsx)(u,{...t})}):u()}},11151:(t,e,n)=>{n.d(e,{Z:()=>a,a:()=>c});var o=n(67294);const r={},i=o.createContext(r);function c(t){const e=o.useContext(i);return o.useMemo((function(){return"function"==typeof t?t(e):{...e,...t}}),[e,t])}function a(t){let e;return e=t.disableParentContext?"function"==typeof t.components?t.components(r):t.components||r:c(t.components),o.createElement(i.Provider,{value:e},t.children)}}}]); \ No newline at end of file +"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[9731],{42286:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>s,contentTitle:()=>c,default:()=>d,frontMatter:()=>i,metadata:()=>a,toc:()=>p});var o=n(85893),r=n(11151);const i={id:"cpp-intro",title:"Introduction",slug:"/"},c=void 0,a={id:"cpp-intro",title:"Introduction",description:"",source:"@site/cpp/00-intro.md",sourceDirName:".",slug:"/",permalink:"/cpp/",draft:!1,unlisted:!1,editUrl:"https://github.com/mfocko/blog/tree/main/cpp/00-intro.md",tags:[],version:"current",lastUpdatedAt:1704558496,formattedLastUpdatedAt:"Jan 6, 2024",sidebarPosition:0,frontMatter:{id:"cpp-intro",title:"Introduction",slug:"/"},sidebar:"autogeneratedBar",next:{title:"Exceptions and RAII",permalink:"/cpp/category/exceptions-and-raii"}},s={},p=[];function u(t){return(0,o.jsx)(o.Fragment,{})}function d(t={}){const{wrapper:e}={...(0,r.a)(),...t.components};return e?(0,o.jsx)(e,{...t,children:(0,o.jsx)(u,{...t})}):u()}},11151:(t,e,n)=>{n.d(e,{Z:()=>a,a:()=>c});var o=n(67294);const r={},i=o.createContext(r);function c(t){const e=o.useContext(i);return o.useMemo((function(){return"function"==typeof t?t(e):{...e,...t}}),[e,t])}function a(t){let e;return e=t.disableParentContext?"function"==typeof t.components?t.components(r):t.components||r:c(t.components),o.createElement(i.Provider,{value:e},t.children)}}}]); \ No newline at end of file diff --git a/assets/js/794ef108.5b256546.js b/assets/js/794ef108.b36337bc.js similarity index 95% rename from assets/js/794ef108.5b256546.js rename to assets/js/794ef108.b36337bc.js index c521a1a..44a7385 100644 --- a/assets/js/794ef108.5b256546.js +++ b/assets/js/794ef108.b36337bc.js @@ -1 +1 @@ -"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[3803],{86427:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>a,contentTitle:()=>s,default:()=>l,frontMatter:()=>i,metadata:()=>c,toc:()=>u});var o=n(85893),r=n(11151);const i={id:"c-intro",title:"Introduction",slug:"/"},s=void 0,c={id:"c-intro",title:"Introduction",description:"",source:"@site/c/00-intro.md",sourceDirName:".",slug:"/",permalink:"/c/",draft:!1,unlisted:!1,editUrl:"https://github.com/mfocko/blog/tree/main/c/00-intro.md",tags:[],version:"current",lastUpdatedAt:1704291155,formattedLastUpdatedAt:"Jan 3, 2024",sidebarPosition:0,frontMatter:{id:"c-intro",title:"Introduction",slug:"/"},sidebar:"autogeneratedBar",next:{title:"Bonuses",permalink:"/c/category/bonuses"}},a={},u=[];function d(t){return(0,o.jsx)(o.Fragment,{})}function l(t={}){const{wrapper:e}={...(0,r.a)(),...t.components};return e?(0,o.jsx)(e,{...t,children:(0,o.jsx)(d,{...t})}):d()}},11151:(t,e,n)=>{n.d(e,{Z:()=>c,a:()=>s});var o=n(67294);const r={},i=o.createContext(r);function s(t){const e=o.useContext(i);return o.useMemo((function(){return"function"==typeof t?t(e):{...e,...t}}),[e,t])}function c(t){let e;return e=t.disableParentContext?"function"==typeof t.components?t.components(r):t.components||r:s(t.components),o.createElement(i.Provider,{value:e},t.children)}}}]); \ No newline at end of file +"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[3803],{86427:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>a,contentTitle:()=>s,default:()=>l,frontMatter:()=>i,metadata:()=>c,toc:()=>u});var o=n(85893),r=n(11151);const i={id:"c-intro",title:"Introduction",slug:"/"},s=void 0,c={id:"c-intro",title:"Introduction",description:"",source:"@site/c/00-intro.md",sourceDirName:".",slug:"/",permalink:"/c/",draft:!1,unlisted:!1,editUrl:"https://github.com/mfocko/blog/tree/main/c/00-intro.md",tags:[],version:"current",lastUpdatedAt:1704558496,formattedLastUpdatedAt:"Jan 6, 2024",sidebarPosition:0,frontMatter:{id:"c-intro",title:"Introduction",slug:"/"},sidebar:"autogeneratedBar",next:{title:"Bonuses",permalink:"/c/category/bonuses"}},a={},u=[];function d(t){return(0,o.jsx)(o.Fragment,{})}function l(t={}){const{wrapper:e}={...(0,r.a)(),...t.components};return e?(0,o.jsx)(e,{...t,children:(0,o.jsx)(d,{...t})}):d()}},11151:(t,e,n)=>{n.d(e,{Z:()=>c,a:()=>s});var o=n(67294);const r={},i=o.createContext(r);function s(t){const e=o.useContext(i);return o.useMemo((function(){return"function"==typeof t?t(e):{...e,...t}}),[e,t])}function c(t){let e;return e=t.disableParentContext?"function"==typeof t.components?t.components(r):t.components||r:s(t.components),o.createElement(i.Provider,{value:e},t.children)}}}]); \ No newline at end of file diff --git a/assets/js/84d1e0d8.e078634a.js b/assets/js/84d1e0d8.f2e0ffd7.js similarity index 94% rename from assets/js/84d1e0d8.e078634a.js rename to assets/js/84d1e0d8.f2e0ffd7.js index d86312a..11fb33d 100644 --- a/assets/js/84d1e0d8.e078634a.js +++ b/assets/js/84d1e0d8.f2e0ffd7.js @@ -1 +1 @@ -"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[1885],{49713:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>c,contentTitle:()=>i,default:()=>u,frontMatter:()=>r,metadata:()=>a,toc:()=>d});var o=n(85893),s=n(11151);const r={id:"algorithms-intro",title:"Introduction",slug:"/"},i=void 0,a={id:"algorithms-intro",title:"Introduction",description:"In this part you can find \u201crandom\u201d additional materials I have written over the",source:"@site/algorithms/00-intro.md",sourceDirName:".",slug:"/",permalink:"/algorithms/",draft:!1,unlisted:!1,editUrl:"https://github.com/mfocko/blog/tree/main/algorithms/00-intro.md",tags:[],version:"current",lastUpdatedAt:1704291155,formattedLastUpdatedAt:"Jan 3, 2024",sidebarPosition:0,frontMatter:{id:"algorithms-intro",title:"Introduction",slug:"/"},sidebar:"autogeneratedBar",next:{title:"Algorithms and Correctness",permalink:"/algorithms/category/algorithms-and-correctness"}},c={},d=[];function l(t){const e={a:"a",em:"em",p:"p",...(0,s.a)(),...t.components};return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)(e.p,{children:["In this part you can find \u201crandom\u201d additional materials I have written over the\ncourse of teaching ",(0,o.jsx)(e.em,{children:"Algorithms and data structures I"}),"."]}),"\n",(0,o.jsx)(e.p,{children:"It is a various mix of stuff that may have been produced as a follow-up on some\nquestion asked at the seminar or spontanously."}),"\n",(0,o.jsxs)(e.p,{children:["If you have some ideas for posts, please do not hesitate to submit them as issues\nin the linked ",(0,o.jsx)(e.a,{href:"https://gitlab.fi.muni.cz/xfocko/kb/issues",children:"GitLab"}),"."]})]})}function u(t={}){const{wrapper:e}={...(0,s.a)(),...t.components};return e?(0,o.jsx)(e,{...t,children:(0,o.jsx)(l,{...t})}):l(t)}},11151:(t,e,n)=>{n.d(e,{Z:()=>a,a:()=>i});var o=n(67294);const s={},r=o.createContext(s);function i(t){const e=o.useContext(r);return o.useMemo((function(){return"function"==typeof t?t(e):{...e,...t}}),[e,t])}function a(t){let e;return e=t.disableParentContext?"function"==typeof t.components?t.components(s):t.components||s:i(t.components),o.createElement(r.Provider,{value:e},t.children)}}}]); \ No newline at end of file +"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[1885],{49713:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>c,contentTitle:()=>i,default:()=>u,frontMatter:()=>r,metadata:()=>a,toc:()=>d});var o=n(85893),s=n(11151);const r={id:"algorithms-intro",title:"Introduction",slug:"/"},i=void 0,a={id:"algorithms-intro",title:"Introduction",description:"In this part you can find \u201crandom\u201d additional materials I have written over the",source:"@site/algorithms/00-intro.md",sourceDirName:".",slug:"/",permalink:"/algorithms/",draft:!1,unlisted:!1,editUrl:"https://github.com/mfocko/blog/tree/main/algorithms/00-intro.md",tags:[],version:"current",lastUpdatedAt:1704558496,formattedLastUpdatedAt:"Jan 6, 2024",sidebarPosition:0,frontMatter:{id:"algorithms-intro",title:"Introduction",slug:"/"},sidebar:"autogeneratedBar",next:{title:"Algorithms and Correctness",permalink:"/algorithms/category/algorithms-and-correctness"}},c={},d=[];function l(t){const e={a:"a",em:"em",p:"p",...(0,s.a)(),...t.components};return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)(e.p,{children:["In this part you can find \u201crandom\u201d additional materials I have written over the\ncourse of teaching ",(0,o.jsx)(e.em,{children:"Algorithms and data structures I"}),"."]}),"\n",(0,o.jsx)(e.p,{children:"It is a various mix of stuff that may have been produced as a follow-up on some\nquestion asked at the seminar or spontanously."}),"\n",(0,o.jsxs)(e.p,{children:["If you have some ideas for posts, please do not hesitate to submit them as issues\nin the linked ",(0,o.jsx)(e.a,{href:"https://gitlab.fi.muni.cz/xfocko/kb/issues",children:"GitLab"}),"."]})]})}function u(t={}){const{wrapper:e}={...(0,s.a)(),...t.components};return e?(0,o.jsx)(e,{...t,children:(0,o.jsx)(l,{...t})}):l(t)}},11151:(t,e,n)=>{n.d(e,{Z:()=>a,a:()=>i});var o=n(67294);const s={},r=o.createContext(s);function i(t){const e=o.useContext(r);return o.useMemo((function(){return"function"==typeof t?t(e):{...e,...t}}),[e,t])}function a(t){let e;return e=t.disableParentContext?"function"==typeof t.components?t.components(s):t.components||s:i(t.components),o.createElement(r.Provider,{value:e},t.children)}}}]); \ No newline at end of file diff --git a/assets/js/b1288602.2a7bb9cd.js b/assets/js/b1288602.fa264713.js similarity index 98% rename from assets/js/b1288602.2a7bb9cd.js rename to assets/js/b1288602.fa264713.js index d565b63..249fede 100644 --- a/assets/js/b1288602.2a7bb9cd.js +++ b/assets/js/b1288602.fa264713.js @@ -1 +1 @@ -"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[59],{51456:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>i,default:()=>d,frontMatter:()=>o,metadata:()=>a,toc:()=>h});var r=t(85893),s=t(11151);const o={title:"Submitting merge requests"},i="Submitting merge requests for review",a={id:"mr",title:"Submitting merge requests",description:"This tutorial aims to show you how to follow basic git workflow and submit changes",source:"@site/c/mr.md",sourceDirName:".",slug:"/mr",permalink:"/c/mr",draft:!1,unlisted:!1,editUrl:"https://github.com/mfocko/blog/tree/main/c/mr.md",tags:[],version:"current",lastUpdatedAt:1704291155,formattedLastUpdatedAt:"Jan 3, 2024",frontMatter:{title:"Submitting merge requests"},sidebar:"autogeneratedBar",previous:{title:"Practice exam C",permalink:"/c/pexam/cams"}},c={},h=[{value:"Tutorial",id:"tutorial",level:2},{value:"Step #1 - Starting from the clean repository",id:"step-1---starting-from-the-clean-repository",level:3},{value:"Step #2 - Create new branch",id:"step-2---create-new-branch",level:3},{value:"Step #3 - Do the assignment",id:"step-3---do-the-assignment",level:3},{value:"Step #4 - Commit and upload the changes to GitLab",id:"step-4---commit-and-upload-the-changes-to-gitlab",level:3},{value:"Step #5 - Creating a merge request manually",id:"step-5---creating-a-merge-request-manually",level:3},{value:"Step #6 - Set assignees",id:"step-6---set-assignees",level:3},{value:"Step #7 - Return to default branch",id:"step-7---return-to-default-branch",level:3}];function l(e){const n={a:"a",blockquote:"blockquote",code:"code",em:"em",h1:"h1",h2:"h2",h3:"h3",hr:"hr",li:"li",ol:"ol",p:"p",pre:"pre",strong:"strong",...(0,s.a)(),...e.components};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(n.h1,{id:"submitting-merge-requests-for-review",children:"Submitting merge requests for review"}),"\n",(0,r.jsxs)(n.p,{children:["This tutorial aims to show you how to follow basic git workflow and submit changes\nthrough ",(0,r.jsx)(n.em,{children:"Merge Requests"})," for review."]}),"\n",(0,r.jsxs)(n.p,{children:["The rudimentary idea behind aims for changes to be present on a separate branch\nthat is supposedly ",(0,r.jsx)(n.em,{children:"merged"})," into the default branch. Till then changes can be reviewed\non ",(0,r.jsx)(n.em,{children:"Merge Request"})," and additional changes may be made based on the reviews. Once\nthe changes satisfy requirements, the merge request is merged."]}),"\n",(0,r.jsx)(n.h2,{id:"tutorial",children:"Tutorial"}),"\n",(0,r.jsxs)(n.blockquote,{children:["\n",(0,r.jsxs)(n.p,{children:["Use this tutorial only for bonus assignments ",(0,r.jsx)(n.strong,{children:"made by your tutors"})," or in case\nyou need to make up for the absence."]}),"\n"]}),"\n",(0,r.jsx)(n.h3,{id:"step-1---starting-from-the-clean-repository",children:"Step #1 - Starting from the clean repository"}),"\n",(0,r.jsxs)(n.p,{children:["In your repository (either locally or on aisa) type ",(0,r.jsx)(n.code,{children:"git status"})," and check if your\nrepository is clean and you are present on the main branch (",(0,r.jsx)(n.code,{children:"master"}),", ",(0,r.jsx)(n.code,{children:"main"})," or\n",(0,r.jsx)(n.code,{children:"trunk"}),"). If you do not know what your default branch is, it is probably ",(0,r.jsx)(n.code,{children:"master"}),"\nand you should not be on any other branch."]}),"\n",(0,r.jsx)(n.p,{children:"Output of the command should look like this:"}),"\n",(0,r.jsx)(n.pre,{children:(0,r.jsx)(n.code,{children:"aisa$ git status\nOn branch master # Or main or trunk.\nYour branch is up to date with 'origin/master'.\n\nnothing to commit, working tree clean\n"})}),"\n",(0,r.jsxs)(n.blockquote,{children:["\n",(0,r.jsxs)(n.p,{children:["In case you are on different branch or there are uncommitted changes,\n",(0,r.jsx)(n.strong,{children:"do not continue!!!"})," Clean your repository (commit the changes or discard\nthem), before you continue."]}),"\n"]}),"\n",(0,r.jsx)(n.h3,{id:"step-2---create-new-branch",children:"Step #2 - Create new branch"}),"\n",(0,r.jsx)(n.p,{children:"In your repository write command:"}),"\n",(0,r.jsx)(n.pre,{children:(0,r.jsx)(n.code,{children:"aisa$ git checkout -b BRANCH\nSwitched to a new branch 'BRANCH'\n"})}),"\n",(0,r.jsxs)(n.p,{children:["Instead of ",(0,r.jsx)(n.code,{children:"BRANCH"})," use some reasonable name for the branch. For example if you\nare working on the seminar from 3rd week, name the branch ",(0,r.jsx)(n.code,{children:"seminar-03"}),"."]}),"\n",(0,r.jsx)(n.h3,{id:"step-3---do-the-assignment",children:"Step #3 - Do the assignment"}),"\n",(0,r.jsx)(n.p,{children:"Download the skeleton for the seminar assignment, extract and program. For example\nif you are working on 3rd seminar, you can do so by:"}),"\n",(0,r.jsx)(n.pre,{children:(0,r.jsx)(n.code,{children:"aisa$ wget https://www.fi.muni.cz/pb071/seminars/seminar-03/pb071-seminar-03.zip\naisa$ unzip pb071-seminar-03.zip\n# Now you should have directory 'seminar-03'.\naisa$ rm pb071-seminar-03.zip\naisa$ cd seminar-03\n# You can work on the assignment.\n"})}),"\n",(0,r.jsx)(n.h3,{id:"step-4---commit-and-upload-the-changes-to-gitlab",children:"Step #4 - Commit and upload the changes to GitLab"}),"\n",(0,r.jsxs)(n.p,{children:["The same way you ",(0,r.jsx)(n.em,{children:"add"})," and ",(0,r.jsx)(n.em,{children:"commit"})," files for the homework assignments, you do for\nthe seminar."]}),"\n",(0,r.jsxs)(n.p,{children:["Now you can upload the changes to GitLab. ",(0,r.jsx)(n.code,{children:"git push"})," is not enough, since repository\non GitLab does not know your new branch. You can solve this by adding arguments:"]}),"\n",(0,r.jsx)(n.pre,{children:(0,r.jsx)(n.code,{children:"aisa$ git push origin BRANCH\n...\nremote: To create a merge request for BRANCH, visit:\nremote: https://gitlab.fi.muni.cz/login/pb071/merge_requests/new?merge_request%5Bsource_branch%5D=BRANCH\n...\n"})}),"\n",(0,r.jsx)(n.p,{children:"In the output you should have a link for creating a merge request. If you see this\nlink, open it and skip next step."}),"\n",(0,r.jsx)(n.h3,{id:"step-5---creating-a-merge-request-manually",children:"Step #5 - Creating a merge request manually"}),"\n",(0,r.jsxs)(n.ol,{children:["\n",(0,r.jsx)(n.li,{children:"Open your repository on GitLab."}),"\n",(0,r.jsxs)(n.li,{children:["On the left panel click on ",(0,r.jsx)(n.em,{children:"Merge Requests"}),"."]}),"\n",(0,r.jsxs)(n.li,{children:["Click on ",(0,r.jsx)(n.em,{children:"New Merge Request"}),"."]}),"\n",(0,r.jsxs)(n.li,{children:["In ",(0,r.jsx)(n.em,{children:"Source branch"})," select ",(0,r.jsx)(n.code,{children:"login/pb071"})," and ",(0,r.jsx)(n.code,{children:"BRANCH"}),", which you created."]}),"\n",(0,r.jsxs)(n.li,{children:["In ",(0,r.jsx)(n.em,{children:"Target branch"})," select ",(0,r.jsx)(n.code,{children:"login/pb071"})," and your default branch you have seen\nin the output of the first command. (most likely ",(0,r.jsx)(n.code,{children:"master"}),")"]}),"\n",(0,r.jsxs)(n.li,{children:["Click on ",(0,r.jsx)(n.em,{children:"Compare branches and continue"}),"."]}),"\n"]}),"\n",(0,r.jsx)(n.h3,{id:"step-6---set-assignees",children:"Step #6 - Set assignees"}),"\n",(0,r.jsxs)(n.p,{children:["On the page that is opened, please check at the top that you are creating merge\nrequest ",(0,r.jsx)(n.strong,{children:"from"})," your new branch ",(0,r.jsx)(n.strong,{children:"to"})," your default branch (one of ",(0,r.jsx)(n.code,{children:"master"}),", ",(0,r.jsx)(n.code,{children:"main"}),"\nor ",(0,r.jsx)(n.code,{children:"trunk"}),")."]}),"\n",(0,r.jsxs)(n.p,{children:["Then in the field ",(0,r.jsx)(n.em,{children:"Assignees"})," set your tutors based on the seminar group. You can\nuse login for a quick look up."]}),"\n",(0,r.jsxs)(n.p,{children:["In the end click on ",(0,r.jsx)(n.em,{children:"Submit merge request"}),"."]}),"\n",(0,r.jsx)(n.h3,{id:"step-7---return-to-default-branch",children:"Step #7 - Return to default branch"}),"\n",(0,r.jsx)(n.p,{children:"Homework assignments can be submitted only from branches specified in the rules\nfor the course. Because of that, before you do anything else, you should switch\nback to your default branch."}),"\n",(0,r.jsxs)(n.p,{children:["First of all, same as in step #1, check that your repository is clean with ",(0,r.jsx)(n.code,{children:"git status"}),".\nFor the sake of safety, do not continue without clean repository. Then with command\n",(0,r.jsx)(n.code,{children:"git checkout BRANCH"})," switch to your default branch ",(0,r.jsx)(n.code,{children:"BRANCH"}),"."]}),"\n",(0,r.jsxs)(n.p,{children:["If you do not know which branch is your default, try ",(0,r.jsx)(n.code,{children:"git branch"})," that outputs all branches in your repository. Default branch is typically ",(0,r.jsx)(n.code,{children:"master"}),", but can\nbe ",(0,r.jsx)(n.code,{children:"main"})," or ",(0,r.jsx)(n.code,{children:"trunk"}),"."]}),"\n",(0,r.jsx)(n.pre,{children:(0,r.jsx)(n.code,{children:"aisa$ git status\n# Check if repository is clean\n\n# If you know, what is your default branch, you can skip next command.\naisa$ git branch\n# Find the default branch in the list; should be one of the `master`, `main` or\n# `trunk` and you should not have more than one of those.\n# In case the list clears the terminal and you cannot see shell prompt, you can\n# press `q` to quit the pager.\n\naisa$ git checkout master\n"})}),"\n",(0,r.jsx)(n.hr,{}),"\n",(0,r.jsxs)(n.p,{children:["Adapted from: ",(0,r.jsx)(n.a,{href:"https://www.fi.muni.cz/~xlacko1/pb071/mr.html",children:"https://www.fi.muni.cz/~xlacko1/pb071/mr.html"})]})]})}function d(e={}){const{wrapper:n}={...(0,s.a)(),...e.components};return n?(0,r.jsx)(n,{...e,children:(0,r.jsx)(l,{...e})}):l(e)}},11151:(e,n,t)=>{t.d(n,{Z:()=>a,a:()=>i});var r=t(67294);const s={},o=r.createContext(s);function i(e){const n=r.useContext(o);return r.useMemo((function(){return"function"==typeof e?e(n):{...n,...e}}),[n,e])}function a(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(s):e.components||s:i(e.components),r.createElement(o.Provider,{value:n},e.children)}}}]); \ No newline at end of file +"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[59],{51456:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>c,contentTitle:()=>i,default:()=>d,frontMatter:()=>o,metadata:()=>a,toc:()=>h});var r=t(85893),s=t(11151);const o={title:"Submitting merge requests"},i="Submitting merge requests for review",a={id:"mr",title:"Submitting merge requests",description:"This tutorial aims to show you how to follow basic git workflow and submit changes",source:"@site/c/mr.md",sourceDirName:".",slug:"/mr",permalink:"/c/mr",draft:!1,unlisted:!1,editUrl:"https://github.com/mfocko/blog/tree/main/c/mr.md",tags:[],version:"current",lastUpdatedAt:1704558496,formattedLastUpdatedAt:"Jan 6, 2024",frontMatter:{title:"Submitting merge requests"},sidebar:"autogeneratedBar",previous:{title:"Practice exam C",permalink:"/c/pexam/cams"}},c={},h=[{value:"Tutorial",id:"tutorial",level:2},{value:"Step #1 - Starting from the clean repository",id:"step-1---starting-from-the-clean-repository",level:3},{value:"Step #2 - Create new branch",id:"step-2---create-new-branch",level:3},{value:"Step #3 - Do the assignment",id:"step-3---do-the-assignment",level:3},{value:"Step #4 - Commit and upload the changes to GitLab",id:"step-4---commit-and-upload-the-changes-to-gitlab",level:3},{value:"Step #5 - Creating a merge request manually",id:"step-5---creating-a-merge-request-manually",level:3},{value:"Step #6 - Set assignees",id:"step-6---set-assignees",level:3},{value:"Step #7 - Return to default branch",id:"step-7---return-to-default-branch",level:3}];function l(e){const n={a:"a",blockquote:"blockquote",code:"code",em:"em",h1:"h1",h2:"h2",h3:"h3",hr:"hr",li:"li",ol:"ol",p:"p",pre:"pre",strong:"strong",...(0,s.a)(),...e.components};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(n.h1,{id:"submitting-merge-requests-for-review",children:"Submitting merge requests for review"}),"\n",(0,r.jsxs)(n.p,{children:["This tutorial aims to show you how to follow basic git workflow and submit changes\nthrough ",(0,r.jsx)(n.em,{children:"Merge Requests"})," for review."]}),"\n",(0,r.jsxs)(n.p,{children:["The rudimentary idea behind aims for changes to be present on a separate branch\nthat is supposedly ",(0,r.jsx)(n.em,{children:"merged"})," into the default branch. Till then changes can be reviewed\non ",(0,r.jsx)(n.em,{children:"Merge Request"})," and additional changes may be made based on the reviews. Once\nthe changes satisfy requirements, the merge request is merged."]}),"\n",(0,r.jsx)(n.h2,{id:"tutorial",children:"Tutorial"}),"\n",(0,r.jsxs)(n.blockquote,{children:["\n",(0,r.jsxs)(n.p,{children:["Use this tutorial only for bonus assignments ",(0,r.jsx)(n.strong,{children:"made by your tutors"})," or in case\nyou need to make up for the absence."]}),"\n"]}),"\n",(0,r.jsx)(n.h3,{id:"step-1---starting-from-the-clean-repository",children:"Step #1 - Starting from the clean repository"}),"\n",(0,r.jsxs)(n.p,{children:["In your repository (either locally or on aisa) type ",(0,r.jsx)(n.code,{children:"git status"})," and check if your\nrepository is clean and you are present on the main branch (",(0,r.jsx)(n.code,{children:"master"}),", ",(0,r.jsx)(n.code,{children:"main"})," or\n",(0,r.jsx)(n.code,{children:"trunk"}),"). If you do not know what your default branch is, it is probably ",(0,r.jsx)(n.code,{children:"master"}),"\nand you should not be on any other branch."]}),"\n",(0,r.jsx)(n.p,{children:"Output of the command should look like this:"}),"\n",(0,r.jsx)(n.pre,{children:(0,r.jsx)(n.code,{children:"aisa$ git status\nOn branch master # Or main or trunk.\nYour branch is up to date with 'origin/master'.\n\nnothing to commit, working tree clean\n"})}),"\n",(0,r.jsxs)(n.blockquote,{children:["\n",(0,r.jsxs)(n.p,{children:["In case you are on different branch or there are uncommitted changes,\n",(0,r.jsx)(n.strong,{children:"do not continue!!!"})," Clean your repository (commit the changes or discard\nthem), before you continue."]}),"\n"]}),"\n",(0,r.jsx)(n.h3,{id:"step-2---create-new-branch",children:"Step #2 - Create new branch"}),"\n",(0,r.jsx)(n.p,{children:"In your repository write command:"}),"\n",(0,r.jsx)(n.pre,{children:(0,r.jsx)(n.code,{children:"aisa$ git checkout -b BRANCH\nSwitched to a new branch 'BRANCH'\n"})}),"\n",(0,r.jsxs)(n.p,{children:["Instead of ",(0,r.jsx)(n.code,{children:"BRANCH"})," use some reasonable name for the branch. For example if you\nare working on the seminar from 3rd week, name the branch ",(0,r.jsx)(n.code,{children:"seminar-03"}),"."]}),"\n",(0,r.jsx)(n.h3,{id:"step-3---do-the-assignment",children:"Step #3 - Do the assignment"}),"\n",(0,r.jsx)(n.p,{children:"Download the skeleton for the seminar assignment, extract and program. For example\nif you are working on 3rd seminar, you can do so by:"}),"\n",(0,r.jsx)(n.pre,{children:(0,r.jsx)(n.code,{children:"aisa$ wget https://www.fi.muni.cz/pb071/seminars/seminar-03/pb071-seminar-03.zip\naisa$ unzip pb071-seminar-03.zip\n# Now you should have directory 'seminar-03'.\naisa$ rm pb071-seminar-03.zip\naisa$ cd seminar-03\n# You can work on the assignment.\n"})}),"\n",(0,r.jsx)(n.h3,{id:"step-4---commit-and-upload-the-changes-to-gitlab",children:"Step #4 - Commit and upload the changes to GitLab"}),"\n",(0,r.jsxs)(n.p,{children:["The same way you ",(0,r.jsx)(n.em,{children:"add"})," and ",(0,r.jsx)(n.em,{children:"commit"})," files for the homework assignments, you do for\nthe seminar."]}),"\n",(0,r.jsxs)(n.p,{children:["Now you can upload the changes to GitLab. ",(0,r.jsx)(n.code,{children:"git push"})," is not enough, since repository\non GitLab does not know your new branch. You can solve this by adding arguments:"]}),"\n",(0,r.jsx)(n.pre,{children:(0,r.jsx)(n.code,{children:"aisa$ git push origin BRANCH\n...\nremote: To create a merge request for BRANCH, visit:\nremote: https://gitlab.fi.muni.cz/login/pb071/merge_requests/new?merge_request%5Bsource_branch%5D=BRANCH\n...\n"})}),"\n",(0,r.jsx)(n.p,{children:"In the output you should have a link for creating a merge request. If you see this\nlink, open it and skip next step."}),"\n",(0,r.jsx)(n.h3,{id:"step-5---creating-a-merge-request-manually",children:"Step #5 - Creating a merge request manually"}),"\n",(0,r.jsxs)(n.ol,{children:["\n",(0,r.jsx)(n.li,{children:"Open your repository on GitLab."}),"\n",(0,r.jsxs)(n.li,{children:["On the left panel click on ",(0,r.jsx)(n.em,{children:"Merge Requests"}),"."]}),"\n",(0,r.jsxs)(n.li,{children:["Click on ",(0,r.jsx)(n.em,{children:"New Merge Request"}),"."]}),"\n",(0,r.jsxs)(n.li,{children:["In ",(0,r.jsx)(n.em,{children:"Source branch"})," select ",(0,r.jsx)(n.code,{children:"login/pb071"})," and ",(0,r.jsx)(n.code,{children:"BRANCH"}),", which you created."]}),"\n",(0,r.jsxs)(n.li,{children:["In ",(0,r.jsx)(n.em,{children:"Target branch"})," select ",(0,r.jsx)(n.code,{children:"login/pb071"})," and your default branch you have seen\nin the output of the first command. (most likely ",(0,r.jsx)(n.code,{children:"master"}),")"]}),"\n",(0,r.jsxs)(n.li,{children:["Click on ",(0,r.jsx)(n.em,{children:"Compare branches and continue"}),"."]}),"\n"]}),"\n",(0,r.jsx)(n.h3,{id:"step-6---set-assignees",children:"Step #6 - Set assignees"}),"\n",(0,r.jsxs)(n.p,{children:["On the page that is opened, please check at the top that you are creating merge\nrequest ",(0,r.jsx)(n.strong,{children:"from"})," your new branch ",(0,r.jsx)(n.strong,{children:"to"})," your default branch (one of ",(0,r.jsx)(n.code,{children:"master"}),", ",(0,r.jsx)(n.code,{children:"main"}),"\nor ",(0,r.jsx)(n.code,{children:"trunk"}),")."]}),"\n",(0,r.jsxs)(n.p,{children:["Then in the field ",(0,r.jsx)(n.em,{children:"Assignees"})," set your tutors based on the seminar group. You can\nuse login for a quick look up."]}),"\n",(0,r.jsxs)(n.p,{children:["In the end click on ",(0,r.jsx)(n.em,{children:"Submit merge request"}),"."]}),"\n",(0,r.jsx)(n.h3,{id:"step-7---return-to-default-branch",children:"Step #7 - Return to default branch"}),"\n",(0,r.jsx)(n.p,{children:"Homework assignments can be submitted only from branches specified in the rules\nfor the course. Because of that, before you do anything else, you should switch\nback to your default branch."}),"\n",(0,r.jsxs)(n.p,{children:["First of all, same as in step #1, check that your repository is clean with ",(0,r.jsx)(n.code,{children:"git status"}),".\nFor the sake of safety, do not continue without clean repository. Then with command\n",(0,r.jsx)(n.code,{children:"git checkout BRANCH"})," switch to your default branch ",(0,r.jsx)(n.code,{children:"BRANCH"}),"."]}),"\n",(0,r.jsxs)(n.p,{children:["If you do not know which branch is your default, try ",(0,r.jsx)(n.code,{children:"git branch"})," that outputs all branches in your repository. Default branch is typically ",(0,r.jsx)(n.code,{children:"master"}),", but can\nbe ",(0,r.jsx)(n.code,{children:"main"})," or ",(0,r.jsx)(n.code,{children:"trunk"}),"."]}),"\n",(0,r.jsx)(n.pre,{children:(0,r.jsx)(n.code,{children:"aisa$ git status\n# Check if repository is clean\n\n# If you know, what is your default branch, you can skip next command.\naisa$ git branch\n# Find the default branch in the list; should be one of the `master`, `main` or\n# `trunk` and you should not have more than one of those.\n# In case the list clears the terminal and you cannot see shell prompt, you can\n# press `q` to quit the pager.\n\naisa$ git checkout master\n"})}),"\n",(0,r.jsx)(n.hr,{}),"\n",(0,r.jsxs)(n.p,{children:["Adapted from: ",(0,r.jsx)(n.a,{href:"https://www.fi.muni.cz/~xlacko1/pb071/mr.html",children:"https://www.fi.muni.cz/~xlacko1/pb071/mr.html"})]})]})}function d(e={}){const{wrapper:n}={...(0,s.a)(),...e.components};return n?(0,r.jsx)(n,{...e,children:(0,r.jsx)(l,{...e})}):l(e)}},11151:(e,n,t)=>{t.d(n,{Z:()=>a,a:()=>i});var r=t(67294);const s={},o=r.createContext(s);function i(e){const n=r.useContext(o);return r.useMemo((function(){return"function"==typeof e?e(n):{...n,...e}}),[n,e])}function a(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(s):e.components||s:i(e.components),r.createElement(o.Provider,{value:n},e.children)}}}]); \ No newline at end of file diff --git a/assets/js/bb882650.6eee4002.js b/assets/js/bb882650.6eee4002.js deleted file mode 100644 index 20c9c36..0000000 --- a/assets/js/bb882650.6eee4002.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[8091],{66765:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>d,contentTitle:()=>i,default:()=>u,frontMatter:()=>r,metadata:()=>s,toc:()=>c});var n=o(85893),a=o(11151);const r={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:!1},i=void 0,s={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:!0,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:!1},unlisted:!1,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"}},d={authorsImageUrls:[void 0]},c=[];function l(e){const t={em:"em",p:"p",...(0,a.a)(),...e.components};return(0,n.jsxs)(t.p,{children:["Let's go through the third week of [",(0,n.jsx)(t.em,{children:"Advent of Code"}),"] in Rust."]})}function u(e={}){const{wrapper:t}={...(0,a.a)(),...e.components};return t?(0,n.jsx)(t,{...e,children:(0,n.jsx)(l,{...e})}):l(e)}},11151:(e,t,o)=>{o.d(t,{Z:()=>s,a:()=>i});var n=o(67294);const a={},r=n.createContext(a);function i(e){const t=n.useContext(r);return n.useMemo((function(){return"function"==typeof e?e(t):{...t,...e}}),[t,e])}function s(e){let t;return t=e.disableParentContext?"function"==typeof e.components?e.components(a):e.components||a:i(e.components),n.createElement(r.Provider,{value:t},e.children)}}}]); \ No newline at end of file diff --git a/assets/js/bb882650.925fdbba.js b/assets/js/bb882650.925fdbba.js new file mode 100644 index 0000000..c089233 --- /dev/null +++ b/assets/js/bb882650.925fdbba.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[8091],{66765:(e,t,o)=>{o.r(t),o.d(t,{assets:()=>d,contentTitle:()=>i,default:()=>u,frontMatter:()=>r,metadata:()=>s,toc:()=>c});var n=o(85893),a=o(11151);const r={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:!1},i=void 0,s={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.57,hasTruncateMarker:!0,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:!1},unlisted:!1,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"}},d={authorsImageUrls:[void 0]},c=[];function l(e){const t={em:"em",p:"p",...(0,a.a)(),...e.components};return(0,n.jsxs)(t.p,{children:["Let's go through the third week of [",(0,n.jsx)(t.em,{children:"Advent of Code"}),"] in Rust."]})}function u(e={}){const{wrapper:t}={...(0,a.a)(),...e.components};return t?(0,n.jsx)(t,{...e,children:(0,n.jsx)(l,{...e})}):l(e)}},11151:(e,t,o)=>{o.d(t,{Z:()=>s,a:()=>i});var n=o(67294);const a={},r=n.createContext(a);function i(e){const t=n.useContext(r);return n.useMemo((function(){return"function"==typeof e?e(t):{...t,...e}}),[t,e])}function s(e){let t;return t=e.disableParentContext?"function"==typeof e.components?e.components(a):e.components||a:i(e.components),n.createElement(r.Provider,{value:t},e.children)}}}]); \ No newline at end of file diff --git a/assets/js/c4c4056e.3de7285f.js b/assets/js/c4c4056e.a7e01235.js similarity index 98% rename from assets/js/c4c4056e.3de7285f.js rename to assets/js/c4c4056e.a7e01235.js index 3625485..81fd4ac 100644 --- a/assets/js/c4c4056e.3de7285f.js +++ b/assets/js/c4c4056e.a7e01235.js @@ -1 +1 @@ -"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[635],{61381:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>l,contentTitle:()=>a,default:()=>d,frontMatter:()=>o,metadata:()=>i,toc:()=>h});var r=n(85893),s=n(11151);const o={id:"index",slug:"/paths/bf-to-astar",title:"From BF to A*",description:"Figuring out shortest-path problem from the BF to the A* algorithm.\n",tags:["cpp","brute force","bellman ford","dynamic programming","dijkstra","greedy","a star"],last_update:{date:new Date("2024-01-01T00:00:00.000Z")}},a=void 0,i={id:"paths/2024-01-01-bf-to-astar/index",title:"From BF to A*",description:"Figuring out shortest-path problem from the BF to the A* algorithm.\n",source:"@site/algorithms/11-paths/2024-01-01-bf-to-astar/index.md",sourceDirName:"11-paths/2024-01-01-bf-to-astar",slug:"/paths/bf-to-astar",permalink:"/algorithms/paths/bf-to-astar",draft:!1,unlisted:!1,editUrl:"https://github.com/mfocko/blog/tree/main/algorithms/11-paths/2024-01-01-bf-to-astar/index.md",tags:[{label:"cpp",permalink:"/algorithms/tags/cpp"},{label:"brute force",permalink:"/algorithms/tags/brute-force"},{label:"bellman ford",permalink:"/algorithms/tags/bellman-ford"},{label:"dynamic programming",permalink:"/algorithms/tags/dynamic-programming"},{label:"dijkstra",permalink:"/algorithms/tags/dijkstra"},{label:"greedy",permalink:"/algorithms/tags/greedy"},{label:"a star",permalink:"/algorithms/tags/a-star"}],version:"current",lastUpdatedAt:1704067200,formattedLastUpdatedAt:"Jan 1, 2024",frontMatter:{id:"index",slug:"/paths/bf-to-astar",title:"From BF to A*",description:"Figuring out shortest-path problem from the BF to the A* algorithm.\n",tags:["cpp","brute force","bellman ford","dynamic programming","dijkstra","greedy","a star"],last_update:{date:"2024-01-01T00:00:00.000Z"}},sidebar:"autogeneratedBar",previous:{title:"Paths in Graphs",permalink:"/algorithms/category/paths-in-graphs"},next:{title:"BF",permalink:"/algorithms/paths/bf-to-astar/bf"}},l={},h=[{value:"Intro",id:"intro",level:2},{value:"Boilerplate",id:"boilerplate",level:2}];function c(t){const e={a:"a",admonition:"admonition",code:"code",em:"em",h2:"h2",li:"li",ol:"ol",p:"p",pre:"pre",strong:"strong",ul:"ul",...(0,s.a)(),...t.components};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(e.h2,{id:"intro",children:"Intro"}),"\n",(0,r.jsx)(e.p,{children:"We will delve into the details and ideas of the most common path-finding\nalgorithms. For the purpose of demonstrating some \u201cfeatures\u201d of the improved\nalgorithms, we will use a 2D map with some rules that will allow us to show cons\nand pros of the shown algorithms."}),"\n",(0,r.jsx)(e.p,{children:"Let's have a look at the example map:"}),"\n",(0,r.jsx)(e.pre,{children:(0,r.jsx)(e.code,{children:"#############\n#..#..*.*.**#\n##***.....**#\n#..########.#\n#...###...#.#\n#..#...##.#.#\n#..#.*.#..#.#\n#....#....#.#\n########*.*.#\n#...........#\n#############\n"})}),"\n",(0,r.jsx)(e.p,{children:"We can see three different kinds of cells:"}),"\n",(0,r.jsxs)(e.ol,{children:["\n",(0,r.jsxs)(e.li,{children:[(0,r.jsx)(e.code,{children:"#"})," which represent walls, that cannot be entered at all"]}),"\n",(0,r.jsxs)(e.li,{children:[(0,r.jsx)(e.code,{children:"*"})," which represent vortices that can be entered at the cost of 5 coins"]}),"\n",(0,r.jsxs)(e.li,{children:[(0,r.jsx)(e.code,{children:"."})," which represent normal cells that can be entered for 1 coin (which is the\nbase price of moving around the map)"]}),"\n"]}),"\n",(0,r.jsx)(e.p,{children:"Let's dissect a specific position on the map to get a better grasp of the rules:"}),"\n",(0,r.jsx)(e.pre,{children:(0,r.jsx)(e.code,{children:" .\n#S*\n .\n"})}),"\n",(0,r.jsxs)(e.p,{children:["We are standing in the cell marked with ",(0,r.jsx)(e.code,{children:"S"})," and we have the following options"]}),"\n",(0,r.jsxs)(e.ul,{children:["\n",(0,r.jsxs)(e.li,{children:["move to the north (",(0,r.jsx)(e.code,{children:"."}),") with the cost of 1 coin,"]}),"\n",(0,r.jsxs)(e.li,{children:["move to the west (",(0,r.jsx)(e.code,{children:"#"}),") ",(0,r.jsx)(e.strong,{children:"is not"})," allowed because of the wall,"]}),"\n",(0,r.jsxs)(e.li,{children:["move to the east (",(0,r.jsx)(e.code,{children:"*"}),") is allowed with the cost of 5 coins, and finally"]}),"\n",(0,r.jsxs)(e.li,{children:["move to the south (",(0,r.jsx)(e.code,{children:"."}),") with the cost of 1 coin."]}),"\n"]}),"\n",(0,r.jsx)(e.admonition,{type:"info",children:(0,r.jsxs)(e.p,{children:["Further on I will follow the same scheme for marking cells with an addition of\n",(0,r.jsx)(e.code,{children:"D"})," to denote the ",(0,r.jsx)(e.em,{children:"destination"})," to which we will be finding the shortest path."]})}),"\n",(0,r.jsx)(e.h2,{id:"boilerplate",children:"Boilerplate"}),"\n",(0,r.jsx)(e.p,{children:"For working with this map I have prepared a basic structure for the graph in C++\nthat will abstract some of the internal workings of our map, namely:"}),"\n",(0,r.jsxs)(e.ul,{children:["\n",(0,r.jsx)(e.li,{children:"remembers the costs of moving around"}),"\n",(0,r.jsxs)(e.li,{children:["provides a simple function that returns price for moving ",(0,r.jsx)(e.strong,{children:"directly"})," between\ntwo positions on the map"]}),"\n",(0,r.jsx)(e.li,{children:"allows us to print the map out, just in case we'd need some adjustments to be\nmade"}),"\n"]}),"\n",(0,r.jsxs)(e.p,{children:["We can see the ",(0,r.jsx)(e.code,{children:"graph"})," header here:"]}),"\n",(0,r.jsx)(e.pre,{children:(0,r.jsx)(e.code,{className:"language-cpp",children:"#ifndef _GRAPH_HPP\n#define _GRAPH_HPP\n\n#include \n#include \n#include \n#include \n#include \n\nusing vertex_t = std::pair;\n\nstruct graph {\n graph(const std::vector>& map)\n : map(map),\n _height(static_cast(map.size())),\n _width(map.empty() ? 0 : static_cast(map[0].size())) {}\n\n static auto unreachable() -> int { return UNREACHABLE; }\n static auto normal_cost() -> int { return NORMAL_COST; }\n static auto vortex_cost() -> int { return VORTEX_COST; }\n\n auto cost(const vertex_t& u, const vertex_t& v) const -> int {\n auto [ux, uy] = u;\n auto [vx, vy] = v;\n\n auto hd = std::abs(ux - vx) + std::abs(uy - vy);\n switch (hd) {\n // \u2039u = v\u203a; staying on the same cell\n case 0:\n return 0;\n // \u2039u\u203a and \u2039v\u203a are neighbours\n case 1:\n break;\n // \u2039u\u203a and \u2039v\u203a are not neighbouring cells\n default:\n return UNREACHABLE;\n }\n\n // boundary check\n if (vy < 0 || vy >= _height || vx < 0 || vx >= _width) {\n return UNREACHABLE;\n }\n\n switch (map[vy][vx]) {\n case '#':\n return UNREACHABLE;\n case '*':\n return VORTEX_COST;\n default:\n return NORMAL_COST;\n }\n }\n\n auto width() const -> int { return _width; }\n auto height() const -> int { return _height; }\n auto has(const vertex_t& v) const -> bool {\n auto [x, y] = v;\n return (0 <= y && y < _height) && (0 <= x && x < _width);\n }\n\n friend std::ostream& operator<<(std::ostream& os, const graph& g);\n\n private:\n std::vector> map;\n int _height, _width;\n\n const static int UNREACHABLE = std::numeric_limits::max();\n // XXX: modify here to change the price of entering the vortex\n const static int VORTEX_COST = 5;\n const static int NORMAL_COST = 1;\n};\n\nstd::ostream& operator<<(std::ostream& os, const graph& g) {\n for (const auto& row : g.map) {\n for (const char cell : row) {\n os << cell;\n }\n os << \"\\n\";\n }\n\n return os;\n}\n\n#endif /* _GRAPH_HPP */\n"})}),"\n",(0,r.jsx)(e.admonition,{title:"Source code",type:"info",children:(0,r.jsxs)(e.p,{children:["You can find all the source code referenced in this series\n",(0,r.jsx)(e.a,{href:"pathname:///files/algorithms/paths/bf-to-astar.tar.gz",children:"here"}),"."]})}),"\n",(0,r.jsx)(e.p,{children:"Let's finally start with some algorithms!"})]})}function d(t={}){const{wrapper:e}={...(0,s.a)(),...t.components};return e?(0,r.jsx)(e,{...t,children:(0,r.jsx)(c,{...t})}):c(t)}},11151:(t,e,n)=>{n.d(e,{Z:()=>i,a:()=>a});var r=n(67294);const s={},o=r.createContext(s);function a(t){const e=r.useContext(o);return r.useMemo((function(){return"function"==typeof t?t(e):{...e,...t}}),[e,t])}function i(t){let e;return e=t.disableParentContext?"function"==typeof t.components?t.components(s):t.components||s:a(t.components),r.createElement(o.Provider,{value:e},t.children)}}}]); \ No newline at end of file +"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[635],{61381:(t,e,n)=>{n.r(e),n.d(e,{assets:()=>l,contentTitle:()=>a,default:()=>d,frontMatter:()=>o,metadata:()=>i,toc:()=>h});var r=n(85893),s=n(11151);const o={id:"index",slug:"/paths/bf-to-astar",title:"From BF to A*",description:"Figuring out shortest-path problem from the BF to the A* algorithm.\n",tags:["cpp","brute force","bellman ford","dynamic programming","dijkstra","greedy","a star"],last_update:{date:new Date("2024-01-01T00:00:00.000Z")}},a=void 0,i={id:"paths/2024-01-01-bf-to-astar/index",title:"From BF to A*",description:"Figuring out shortest-path problem from the BF to the A* algorithm.\n",source:"@site/algorithms/11-paths/2024-01-01-bf-to-astar/index.md",sourceDirName:"11-paths/2024-01-01-bf-to-astar",slug:"/paths/bf-to-astar",permalink:"/algorithms/paths/bf-to-astar",draft:!1,unlisted:!1,editUrl:"https://github.com/mfocko/blog/tree/main/algorithms/11-paths/2024-01-01-bf-to-astar/index.md",tags:[{label:"cpp",permalink:"/algorithms/tags/cpp"},{label:"brute force",permalink:"/algorithms/tags/brute-force"},{label:"bellman ford",permalink:"/algorithms/tags/bellman-ford"},{label:"dynamic programming",permalink:"/algorithms/tags/dynamic-programming"},{label:"dijkstra",permalink:"/algorithms/tags/dijkstra"},{label:"greedy",permalink:"/algorithms/tags/greedy"},{label:"a star",permalink:"/algorithms/tags/a-star"}],version:"current",lastUpdatedAt:1704067200,formattedLastUpdatedAt:"Jan 1, 2024",frontMatter:{id:"index",slug:"/paths/bf-to-astar",title:"From BF to A*",description:"Figuring out shortest-path problem from the BF to the A* algorithm.\n",tags:["cpp","brute force","bellman ford","dynamic programming","dijkstra","greedy","a star"],last_update:{date:"2024-01-01T00:00:00.000Z"}},sidebar:"autogeneratedBar",previous:{title:"Paths in Graphs",permalink:"/algorithms/category/paths-in-graphs"},next:{title:"BF",permalink:"/algorithms/paths/bf-to-astar/bf"}},l={},h=[{value:"Intro",id:"intro",level:2},{value:"Boilerplate",id:"boilerplate",level:2}];function c(t){const e={a:"a",admonition:"admonition",code:"code",em:"em",h2:"h2",li:"li",ol:"ol",p:"p",pre:"pre",strong:"strong",ul:"ul",...(0,s.a)(),...t.components};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(e.h2,{id:"intro",children:"Intro"}),"\n",(0,r.jsx)(e.p,{children:"We will delve into the details and ideas of the most common path-finding\nalgorithms. For the purpose of demonstrating some \u201cfeatures\u201d of the improved\nalgorithms, we will use a 2D map with some rules that will allow us to show cons\nand pros of the shown algorithms."}),"\n",(0,r.jsx)(e.p,{children:"Let's have a look at the example map:"}),"\n",(0,r.jsx)(e.pre,{children:(0,r.jsx)(e.code,{children:"#############\n#..#..*.*.**#\n##***.....**#\n#..########.#\n#...###...#.#\n#..#...##.#.#\n#..#.*.#..#.#\n#....#....#.#\n########*.*.#\n#...........#\n#############\n"})}),"\n",(0,r.jsx)(e.p,{children:"We can see three different kinds of cells:"}),"\n",(0,r.jsxs)(e.ol,{children:["\n",(0,r.jsxs)(e.li,{children:[(0,r.jsx)(e.code,{children:"#"})," which represent walls, that cannot be entered at all"]}),"\n",(0,r.jsxs)(e.li,{children:[(0,r.jsx)(e.code,{children:"*"})," which represent vortices that can be entered at the cost of 5 coins"]}),"\n",(0,r.jsxs)(e.li,{children:[(0,r.jsx)(e.code,{children:"."})," which represent normal cells that can be entered for 1 coin (which is the\nbase price of moving around the map)"]}),"\n"]}),"\n",(0,r.jsx)(e.p,{children:"Let's dissect a specific position on the map to get a better grasp of the rules:"}),"\n",(0,r.jsx)(e.pre,{children:(0,r.jsx)(e.code,{children:" .\n#S*\n .\n"})}),"\n",(0,r.jsxs)(e.p,{children:["We are standing in the cell marked with ",(0,r.jsx)(e.code,{children:"S"})," and we have the following options"]}),"\n",(0,r.jsxs)(e.ul,{children:["\n",(0,r.jsxs)(e.li,{children:["move to the north (",(0,r.jsx)(e.code,{children:"."}),") with the cost of 1 coin,"]}),"\n",(0,r.jsxs)(e.li,{children:["move to the west (",(0,r.jsx)(e.code,{children:"#"}),") ",(0,r.jsx)(e.strong,{children:"is not"})," allowed because of the wall,"]}),"\n",(0,r.jsxs)(e.li,{children:["move to the east (",(0,r.jsx)(e.code,{children:"*"}),") is allowed with the cost of 5 coins, and finally"]}),"\n",(0,r.jsxs)(e.li,{children:["move to the south (",(0,r.jsx)(e.code,{children:"."}),") with the cost of 1 coin."]}),"\n"]}),"\n",(0,r.jsx)(e.admonition,{type:"info",children:(0,r.jsxs)(e.p,{children:["Further on I will follow the same scheme for marking cells with an addition of\n",(0,r.jsx)(e.code,{children:"D"})," to denote the ",(0,r.jsx)(e.em,{children:"destination"})," to which we will be finding the shortest path."]})}),"\n",(0,r.jsx)(e.h2,{id:"boilerplate",children:"Boilerplate"}),"\n",(0,r.jsx)(e.p,{children:"For working with this map I have prepared a basic structure for the graph in C++\nthat will abstract some of the internal workings of our map, namely:"}),"\n",(0,r.jsxs)(e.ul,{children:["\n",(0,r.jsx)(e.li,{children:"remembers the costs of moving around"}),"\n",(0,r.jsxs)(e.li,{children:["provides a simple function that returns price for moving ",(0,r.jsx)(e.strong,{children:"directly"})," between\ntwo positions on the map"]}),"\n",(0,r.jsx)(e.li,{children:"allows us to print the map out, just in case we'd need some adjustments to be\nmade"}),"\n"]}),"\n",(0,r.jsxs)(e.p,{children:["We can see the ",(0,r.jsx)(e.code,{children:"graph"})," header here:"]}),"\n",(0,r.jsx)(e.pre,{children:(0,r.jsx)(e.code,{className:"language-cpp",children:"#ifndef _GRAPH_HPP\n#define _GRAPH_HPP\n\n#include \n#include \n#include \n#include \n#include \n\nusing vertex_t = std::pair;\n\nstruct graph {\n graph(const std::vector>& map)\n : map(map),\n _height(static_cast(map.size())),\n _width(map.empty() ? 0 : static_cast(map[0].size())) {}\n\n static auto unreachable() -> int { return UNREACHABLE; }\n static auto normal_cost() -> int { return NORMAL_COST; }\n static auto vortex_cost() -> int { return VORTEX_COST; }\n\n auto cost(const vertex_t& u, const vertex_t& v) const -> int {\n auto [ux, uy] = u;\n auto [vx, vy] = v;\n\n auto md = std::abs(ux - vx) + std::abs(uy - vy);\n switch (md) {\n // \u2039u = v\u203a; staying on the same cell\n case 0:\n return 0;\n // \u2039u\u203a and \u2039v\u203a are neighbours\n case 1:\n break;\n // \u2039u\u203a and \u2039v\u203a are not neighbouring cells\n default:\n return UNREACHABLE;\n }\n\n // boundary check\n if (vy < 0 || vy >= _height || vx < 0 || vx >= _width) {\n return UNREACHABLE;\n }\n\n switch (map[vy][vx]) {\n case '#':\n return UNREACHABLE;\n case '*':\n return VORTEX_COST;\n default:\n return NORMAL_COST;\n }\n }\n\n auto width() const -> int { return _width; }\n auto height() const -> int { return _height; }\n auto has(const vertex_t& v) const -> bool {\n auto [x, y] = v;\n return (0 <= y && y < _height) && (0 <= x && x < _width);\n }\n\n friend std::ostream& operator<<(std::ostream& os, const graph& g);\n\n private:\n std::vector> map;\n int _height, _width;\n\n const static int UNREACHABLE = std::numeric_limits::max();\n // XXX: modify here to change the price of entering the vortex\n const static int VORTEX_COST = 5;\n const static int NORMAL_COST = 1;\n};\n\nstd::ostream& operator<<(std::ostream& os, const graph& g) {\n for (const auto& row : g.map) {\n for (const char cell : row) {\n os << cell;\n }\n os << \"\\n\";\n }\n\n return os;\n}\n\n#endif /* _GRAPH_HPP */\n"})}),"\n",(0,r.jsx)(e.admonition,{title:"Source code",type:"info",children:(0,r.jsxs)(e.p,{children:["You can find all the source code referenced in this series\n",(0,r.jsx)(e.a,{href:"pathname:///files/algorithms/paths/bf-to-astar.tar.gz",children:"here"}),"."]})}),"\n",(0,r.jsx)(e.p,{children:"Let's finally start with some algorithms!"})]})}function d(t={}){const{wrapper:e}={...(0,s.a)(),...t.components};return e?(0,r.jsx)(e,{...t,children:(0,r.jsx)(c,{...t})}):c(t)}},11151:(t,e,n)=>{n.d(e,{Z:()=>i,a:()=>a});var r=n(67294);const s={},o=r.createContext(s);function a(t){const e=r.useContext(o);return r.useMemo((function(){return"function"==typeof t?t(e):{...e,...t}}),[e,t])}function i(t){let e;return e=t.disableParentContext?"function"==typeof t.components?t.components(s):t.components||s:a(t.components),r.createElement(o.Provider,{value:e},t.children)}}}]); \ No newline at end of file diff --git a/assets/js/cfa2b263.ce80265a.js b/assets/js/cfa2b263.ce80265a.js new file mode 100644 index 0000000..0865ae2 --- /dev/null +++ b/assets/js/cfa2b263.ce80265a.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[3086],{34437:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>l,contentTitle:()=>r,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>d});var i=n(85893),a=n(11151);const o={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:!1},r=void 0,s={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:!0,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:!1},unlisted:!1,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"}},l={authorsImageUrls:[void 0]},d=[{value:"Problem description",id:"problem-description",level:2},{value:"Example",id:"example",level:3},{value:"Skeleton and initial adjustments",id:"skeleton-and-initial-adjustments",level:2},{value:"Na\xefve solution",id:"na\xefve-solution",level:2},{value:"Implementing the diagonals",id:"implementing-the-diagonals",level:2},{value:"Iterating over diagonals",id:"iterating-over-diagonals",level:3},{value:"Implementing the iterator over diagonals",id:"implementing-the-iterator-over-diagonals",level:3},{value:"Implementing the diagonal itself",id:"implementing-the-diagonal-itself",level:2},{value:"Implementing diagonal_iter",id:"implementing-diagonal_iter",level:3}];function c(e){const t={a:"a",admonition:"admonition",blockquote:"blockquote",code:"code",em:"em",h2:"h2",h3:"h3",img:"img",li:"li",ol:"ol",p:"p",pre:"pre",section:"section",strong:"strong",sup:"sup",ul:"ul",...(0,a.a)(),...e.components};return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(t.p,{children:"Let's try to solve one of the LeetCode challenges in easy and hard mode at the\nsame time."}),"\n",(0,i.jsxs)(t.ul,{children:["\n",(0,i.jsxs)(t.li,{children:["Link to the problem: ",(0,i.jsx)(t.a,{href:"https://leetcode.com/problems/sort-the-matrix-diagonally/",children:"https://leetcode.com/problems/sort-the-matrix-diagonally/"})]}),"\n"]}),"\n",(0,i.jsx)(t.h2,{id:"problem-description",children:"Problem description"}),"\n",(0,i.jsxs)(t.p,{children:["A ",(0,i.jsx)(t.strong,{children:"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 ",(0,i.jsx)(t.strong,{children:"matrix diagonal"})," starting\nfrom ",(0,i.jsx)(t.code,{children:"mat[2][0]"}),", where ",(0,i.jsx)(t.code,{children:"mat"})," is a ",(0,i.jsx)(t.code,{children:"6 x 3"})," matrix, includes cells ",(0,i.jsx)(t.code,{children:"mat[2][0]"}),",\n",(0,i.jsx)(t.code,{children:"mat[3][1]"}),", and ",(0,i.jsx)(t.code,{children:"mat[4][2]"}),"."]}),"\n",(0,i.jsxs)(t.p,{children:["Given an ",(0,i.jsx)(t.code,{children:"m x n"})," matrix ",(0,i.jsx)(t.code,{children:"mat"})," of integers, sort each matrix diagonal in ascending\norder and return the resulting matrix."]}),"\n",(0,i.jsx)(t.h3,{id:"example",children:"Example"}),"\n",(0,i.jsx)(t.p,{children:(0,i.jsx)(t.img,{src:"https://assets.leetcode.com/uploads/2020/01/21/1482_example_1_2.png",alt:"Image describing the problem"})}),"\n",(0,i.jsx)(t.h2,{id:"skeleton-and-initial-adjustments",children:"Skeleton and initial adjustments"}),"\n",(0,i.jsx)(t.p,{children:"We are given the following skeleton for the C++ and the given challenge:"}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-cpp",children:"class Solution {\npublic:\n vector> diagonalSort(vector>& mat) {\n\n }\n};\n"})}),"\n",(0,i.jsxs)(t.p,{children:["The 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 ",(0,i.jsx)(t.code,{children:"vector"})," header and using\nfully-qualified namespaces",(0,i.jsx)(t.sup,{children:(0,i.jsx)(t.a,{href:"#user-content-fn-1-b611be",id:"user-content-fnref-1-b611be","data-footnote-ref":!0,"aria-describedby":"footnote-label",children:"1"})})," and also adding few tests:"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-cpp",children:"#include \n#include \n\nusing matrix = std::vector>;\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",(0,i.jsx)(t.p,{children:"We 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",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-diff",children:"- matrix diagonalSort(matrix& mat)\n+ matrix diagonalSort(matrix mat)\n {\n+ return mat;\n }\n"})}),"\n",(0,i.jsx)(t.p,{children:"Now, we get the copy and we're good to go."}),"\n",(0,i.jsx)(t.h2,{id:"na\xefve-solution",children:"Na\xefve solution"}),"\n",(0,i.jsx)(t.p,{children:"As 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",(0,i.jsxs)(t.p,{children:["What does that mean for us? Well, we have an ",(0,i.jsx)(t.code,{children:"std::sort"}),", we can use it, right?\nLet's have a look at it:"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-cpp",children:"template< class RandomIt >\nvoid sort( RandomIt first, RandomIt last );\n"})}),"\n",(0,i.jsxs)(t.p,{children:["This overload is more than we need. What does it do? It just sorts the elements\nin the range ",(0,i.jsx)(t.code,{children:"[first, last)"})," using ",(0,i.jsx)(t.code,{children:"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",(0,i.jsxs)(t.p,{children:["What is the ",(0,i.jsx)(t.code,{children:"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 ",(0,i.jsx)(t.em,{children:"random access"}),"\n",(0,i.jsx)(t.em,{children:"iterator"})," and allows swapping its values at the same time."]}),"\n",(0,i.jsxs)(t.admonition,{title:"Random access iterator",type:"tip",children:[(0,i.jsxs)(t.p,{children:["What is the ",(0,i.jsx)(t.em,{children:"random access iterator"})," though? We can find it in a documentation\nand see the following description:"]}),(0,i.jsxs)(t.blockquote,{children:["\n",(0,i.jsxs)(t.p,{children:["A ",(0,i.jsx)(t.strong,{children:"LegacyRandomAccessIterator"})," is a ",(0,i.jsx)(t.a,{href:"https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator",children:"LegacyBidirectionalIterator"}),"\nthat can be moved to point to any element in constant time."]}),"\n"]}),(0,i.jsxs)(t.p,{children:["After 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",(0,i.jsx)(t.em,{children:"compiler-assisted development"}),"\u201d",(0,i.jsx)(t.sup,{children:(0,i.jsx)(t.a,{href:"#user-content-fn-2-b611be",id:"user-content-fnref-2-b611be","data-footnote-ref":!0,"aria-describedby":"footnote-label",children:"2"})})," if you will ;)"]})]}),"\n",(0,i.jsxs)(t.p,{children:["Now we know that we can use ",(0,i.jsx)(t.code,{children:"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",(0,i.jsx)(t.sup,{children:(0,i.jsx)(t.a,{href:"#user-content-fn-3-b611be",id:"user-content-fnref-3-b611be","data-footnote-ref":!0,"aria-describedby":"footnote-label",children:"3"})}),". And that way we get"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-cpp",children:"matrix 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",(0,i.jsx)(t.p,{children:"This solution looks very simple, doesn't it? Well, cause it is.\nLet's try compiling it:"}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{children:"matrix-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",(0,i.jsxs)(t.p,{children:["OK, seems about right. We haven't implemented the ",(0,i.jsx)(t.code,{children:"diagonals"})," yet. And based on\nwhat we've written so far, we need a function or a class ",(0,i.jsx)(t.code,{children:"diagonals"})," that will\ngive us the diagonals we need."]}),"\n",(0,i.jsxs)(t.h2,{id:"implementing-the-diagonals",children:["Implementing the ",(0,i.jsx)(t.code,{children:"diagonals"})]}),"\n",(0,i.jsxs)(t.p,{children:["Cool, so we need the function that will let us go through each and every diagonal\nin our matrix. We use the ",(0,i.jsx)(t.em,{children:"for-range"})," loop, so whatever we get back from the\n",(0,i.jsx)(t.code,{children:"diagonals"})," must support ",(0,i.jsx)(t.code,{children:".begin()"})," and ",(0,i.jsx)(t.code,{children:".end()"}),". Since I am a masochist, we will\ndo such functionality for a matrix of any type, not just the ",(0,i.jsx)(t.code,{children:"int"})," from the challenge."]}),"\n",(0,i.jsx)(t.p,{children:"As I said, we need to be able to"}),"\n",(0,i.jsxs)(t.ul,{children:["\n",(0,i.jsx)(t.li,{children:"construct the object"}),"\n",(0,i.jsx)(t.li,{children:"get the beginning"}),"\n",(0,i.jsx)(t.li,{children:"get the end (the \u201csentinel\u201d)"}),"\n"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-cpp",children:"template \nclass diagonals {\n using matrix_t = std::vector>;\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",(0,i.jsxs)(t.p,{children:["Now we have a ",(0,i.jsx)(t.code,{children:"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",(0,i.jsxs)(t.p,{children:["We have a templated class with templated ",(0,i.jsx)(t.code,{children:"T"})," that is used as a placeholder for any\ntype we would store in the matrix. Because I'm lazy, I have defined the ",(0,i.jsx)(t.code,{children:"matrix_t"}),"\ntype that is a \u201cshortcut\u201d for ",(0,i.jsx)(t.code,{children:"std::vector>"}),", 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 ",(0,i.jsx)(t.em,{children:"for-range"}),"."]}),"\n",(0,i.jsx)(t.h3,{id:"iterating-over-diagonals",children:"Iterating over diagonals"}),"\n",(0,i.jsxs)(t.p,{children:["Now 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,i.jsx)(t.code,{children:"(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",(0,i.jsx)(t.p,{children:"We 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",(0,i.jsxs)(t.p,{children:["We will start by updating the ",(0,i.jsx)(t.code,{children:"begin"})," and ",(0,i.jsx)(t.code,{children:"end"})," to reflect our choice accordingly."]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-cpp",children:"diagonals_iter begin() { return diagonals_iter { _matrix, 0, 0 }; }\ndiagonals_iter end() { return diagonals_iter { _matrix, 0, _matrix.size() }; }\n"})}),"\n",(0,i.jsxs)(t.p,{children:["For the ",(0,i.jsx)(t.code,{children:"begin"})," we return the first diagonal that starts at ",(0,i.jsx)(t.code,{children:"(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,i.jsx)(t.code,{children:"(0, height)"}),". Apart from the\nindices, we also need to pass reference to the matrix itself."]}),"\n",(0,i.jsx)(t.admonition,{type:"note",children:(0,i.jsxs)(t.p,{children:["You may have noticed that we also include the diagonals that have length 1,\nspecifically the ones at ",(0,i.jsx)(t.code,{children:"(0, height - 1)"})," and ",(0,i.jsx)(t.code,{children:"(width - 1, 0)"}),". We are implementing\nan iterator that ",(0,i.jsx)(t.strong,{children:"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",(0,i.jsxs)(t.p,{children:["Cool, let's leave the iterator itself to someone else, right?",(0,i.jsx)(t.sup,{children:(0,i.jsx)(t.a,{href:"#user-content-fn-4-b611be",id:"user-content-fnref-4-b611be","data-footnote-ref":!0,"aria-describedby":"footnote-label",children:"4"})})]}),"\n",(0,i.jsx)(t.h3,{id:"implementing-the-iterator-over-diagonals",children:"Implementing the iterator over diagonals"}),"\n",(0,i.jsxs)(t.p,{children:["We can start with a simple skeleton based on the information that we pass from\nthe ",(0,i.jsx)(t.code,{children:"diagonals"}),". Also to utilize the ",(0,i.jsx)(t.code,{children:"matrix_t"})," and also contain implementation\ndetails hidden away, we will put this code into the ",(0,i.jsx)(t.code,{children:"diagonals"})," class."]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-cpp",children:"class 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",(0,i.jsx)(t.p,{children:"In 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",(0,i.jsxs)(t.ul,{children:["\n",(0,i.jsx)(t.li,{children:"inequality operator (we need to know when we reach the end and have nothing to\niterate over)"}),"\n",(0,i.jsx)(t.li,{children:"preincrementation operator (we need to be able to move around the iterable)"}),"\n",(0,i.jsx)(t.li,{children:"dereference operator (we need to be able to retrieve the objects we iterate\nover)"}),"\n"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-cpp",children:"class 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 operator*() const { return diagonal { m, x, y }; }\n};\n"})}),"\n",(0,i.jsx)(t.p,{children:"Let'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",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-diff",children:"- return m != rhs.m || x != rhs.x || y != rhs.y;\n+ return x != rhs.x || y != rhs.y || m != rhs.m;\n"})}),"\n",(0,i.jsx)(t.p,{children:"Preincrementation is where the magic happens. If you have a better look, you can\nsee two branches of this operation:"}),"\n",(0,i.jsxs)(t.ol,{children:["\n",(0,i.jsxs)(t.li,{children:["When ",(0,i.jsx)(t.code,{children:"y != 0"})," (we're iterating over the diagonals in the first column)\nIn this case, we just bump the row and we're done."]}),"\n",(0,i.jsxs)(t.li,{children:["When ",(0,i.jsx)(t.code,{children:"y == 0"})," (we're iterating over the diagonals in the first row)\nIn this case, we bump the column and check if we haven't gotten out of bounds,\ni.e. the end of the first row. If we get out of the bounds, we're continuing\nwith the second diagonal in the first column."]}),"\n"]}),"\n",(0,i.jsxs)(t.p,{children:["Dereferencing 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 ",(0,i.jsx)(t.code,{children:"diagonal"}),"."]}),"\n",(0,i.jsxs)(t.h2,{id:"implementing-the-diagonal-itself",children:["Implementing the ",(0,i.jsx)(t.code,{children:"diagonal"})," itself"]}),"\n",(0,i.jsxs)(t.p,{children:["After 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 ",(0,i.jsx)(t.code,{children:"std::sort"}),"\nfunction. We can start with the following skeleton:"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-cpp",children:"template \nclass diagonal {\n using matrix_t = std::vector>;\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",(0,i.jsxs)(t.p,{children:["Initialization is rather simple, we just \u201ckeep\u201d the stuff we get, ",(0,i.jsx)(t.code,{children:"begin"})," is the\nsimplest, we just delegate."]}),"\n",(0,i.jsxs)(t.p,{children:["In case of the ",(0,i.jsx)(t.code,{children:"end"}),", it gets more complicated. We need to know where is the \u201cend\u201d\nof the diagonal. Since ",(0,i.jsx)(t.code,{children:"end"})," should point to the first element \u201cafter\u201d the iterable,\nwe know that it's the first position of the iterator where either ",(0,i.jsx)(t.code,{children:"y"})," becomes\n",(0,i.jsx)(t.code,{children:"matrix.size()"})," or ",(0,i.jsx)(t.code,{children:"x"})," becomes ",(0,i.jsx)(t.code,{children:"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 ",(0,i.jsx)(t.code,{children:"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",(0,i.jsx)(t.p,{children:"Now we just need to finish the iterator for the diagonal itself and we're done."}),"\n",(0,i.jsxs)(t.h3,{id:"implementing-diagonal_iter",children:["Implementing ",(0,i.jsx)(t.code,{children:"diagonal_iter"})]}),"\n",(0,i.jsxs)(t.p,{children:["This part is the hardest from all we need to do. It's because of the requirements\nof the ",(0,i.jsx)(t.code,{children:"std::sort"})," that requires us to implement a ",(0,i.jsx)(t.em,{children:"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",(0,i.jsxs)(t.p,{children:["Let's go through all of the functionality that our iterator needs to support to\nbe used in ",(0,i.jsx)(t.code,{children:"std::sort"}),". We need the usual operations like:"]}),"\n",(0,i.jsxs)(t.ul,{children:["\n",(0,i.jsx)(t.li,{children:"equality/inequality"}),"\n",(0,i.jsx)(t.li,{children:"incrementation"}),"\n",(0,i.jsx)(t.li,{children:"dereferencing"}),"\n"]}),"\n",(0,i.jsx)(t.p,{children:"We will also add all the types that our iterator uses with the category of the\niterator, i.e. what interface it supports:"}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-cpp",children:"class 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",(0,i.jsxs)(t.p,{children:["This is pretty similar to the previous iterator, but now we need to implement the\nremaining requirements of the ",(0,i.jsx)(t.em,{children:"random access iterator"}),". Let's see what those are:"]}),"\n",(0,i.jsxs)(t.ul,{children:["\n",(0,i.jsxs)(t.li,{children:["decrementation - cause we need to be able to move backwards too, since _random _\n",(0,i.jsx)(t.em,{children:"access iterator"})," extends the interface of ",(0,i.jsx)(t.em,{children:"bidirectional iterator"})]}),"\n",(0,i.jsx)(t.li,{children:"moving the iterator in either direction by steps given as an integer"}),"\n",(0,i.jsx)(t.li,{children:"being able to tell the distance between two iterators"}),"\n",(0,i.jsx)(t.li,{children:"define an ordering on the iterators"}),"\n"]}),"\n",(0,i.jsx)(t.p,{children:"Let's fill them in:"}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-cpp",children:"class 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",(0,i.jsx)(t.p,{children:"At 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",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{children:"/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1792:11: error: object of type 'diagonal::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_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_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_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_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_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::matrix_t &' (aka 'vector> &')\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_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_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_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_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::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::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_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_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_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::matrix_t &' (aka 'vector> &')\n matrix_t& m;\n ^\n"})}),"\n",(0,i.jsx)(t.p,{children:"That's a lot of noise, isn't it? Let's focus on the important parts:"}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{children:"/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1792:11: error: object of type 'diagonal::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::matrix_t &' (aka 'vector> &')\n matrix_t& m;\n ^\n"})}),"\n",(0,i.jsx)(t.p,{children:"Ah! 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",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-diff",children:"# we need to keep a different type than reference\n- matrix_t& m;\n+ std::reference_wrapper 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",(0,i.jsxs)(t.p,{children:["We're done now! We have written an iterator over diagonals for a 2D ",(0,i.jsx)(t.code,{children:"vector"}),". You can have a look at the final result ",(0,i.jsx)(t.a,{href:"pathname:///files/blog/leetcode/sort-matrix-diagonally/matrix-sort.cpp",children:"here"}),"."]}),"\n",(0,i.jsxs)(t.section,{"data-footnotes":!0,className:"footnotes",children:[(0,i.jsx)(t.h2,{className:"sr-only",id:"footnote-label",children:"Footnotes"}),"\n",(0,i.jsxs)(t.ol,{children:["\n",(0,i.jsxs)(t.li,{id:"user-content-fn-1-b611be",children:["\n",(0,i.jsxs)(t.p,{children:["just because I'm used to it and don't care about your opinion ;) ",(0,i.jsx)(t.a,{href:"#user-content-fnref-1-b611be","data-footnote-backref":"","aria-label":"Back to reference 1",className:"data-footnote-backref",children:"\u21a9"})]}),"\n"]}),"\n",(0,i.jsxs)(t.li,{id:"user-content-fn-2-b611be",children:["\n",(0,i.jsxs)(t.p,{children:["exercise at your own risk ",(0,i.jsx)(t.a,{href:"#user-content-fnref-2-b611be","data-footnote-backref":"","aria-label":"Back to reference 2",className:"data-footnote-backref",children:"\u21a9"})]}),"\n"]}),"\n",(0,i.jsxs)(t.li,{id:"user-content-fn-3-b611be",children:["\n",(0,i.jsxs)(t.p,{children:["me in 5 minutes in fact, but don't make me scared ",(0,i.jsx)(t.a,{href:"#user-content-fnref-3-b611be","data-footnote-backref":"","aria-label":"Back to reference 3",className:"data-footnote-backref",children:"\u21a9"})]}),"\n"]}),"\n",(0,i.jsxs)(t.li,{id:"user-content-fn-4-b611be",children:["\n",(0,i.jsxs)(t.p,{children:["me in the next section\u2026 ",(0,i.jsx)(t.a,{href:"#user-content-fnref-4-b611be","data-footnote-backref":"","aria-label":"Back to reference 4",className:"data-footnote-backref",children:"\u21a9"})]}),"\n"]}),"\n"]}),"\n"]})]})}function h(e={}){const{wrapper:t}={...(0,a.a)(),...e.components};return t?(0,i.jsx)(t,{...e,children:(0,i.jsx)(c,{...e})}):c(e)}},11151:(e,t,n)=>{n.d(t,{Z:()=>s,a:()=>r});var i=n(67294);const a={},o=i.createContext(a);function r(e){const t=i.useContext(o);return i.useMemo((function(){return"function"==typeof e?e(t):{...t,...e}}),[t,e])}function s(e){let t;return t=e.disableParentContext?"function"==typeof e.components?e.components(a):e.components||a:r(e.components),i.createElement(o.Provider,{value:t},e.children)}}}]); \ No newline at end of file diff --git a/assets/js/cfa2b263.efd5103c.js b/assets/js/cfa2b263.efd5103c.js deleted file mode 100644 index 3395734..0000000 --- a/assets/js/cfa2b263.efd5103c.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[3086],{34437:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>l,contentTitle:()=>r,default:()=>h,frontMatter:()=>o,metadata:()=>s,toc:()=>d});var i=n(85893),a=n(11151);const o={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:!1},r=void 0,s={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:!0,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:!1},unlisted:!1,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"}},l={authorsImageUrls:[void 0]},d=[{value:"Problem description",id:"problem-description",level:2},{value:"Example",id:"example",level:3},{value:"Skeleton and initial adjustments",id:"skeleton-and-initial-adjustments",level:2},{value:"Na\xefve solution",id:"na\xefve-solution",level:2},{value:"Implementing the diagonals",id:"implementing-the-diagonals",level:2},{value:"Iterating over diagonals",id:"iterating-over-diagonals",level:3},{value:"Implementing the iterator over diagonals",id:"implementing-the-iterator-over-diagonals",level:3},{value:"Implementing the diagonal itself",id:"implementing-the-diagonal-itself",level:2},{value:"Implementing diagonal_iter",id:"implementing-diagonal_iter",level:3}];function c(e){const t={a:"a",admonition:"admonition",blockquote:"blockquote",code:"code",em:"em",h2:"h2",h3:"h3",img:"img",li:"li",ol:"ol",p:"p",pre:"pre",section:"section",strong:"strong",sup:"sup",ul:"ul",...(0,a.a)(),...e.components};return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(t.p,{children:"Let's try to solve one of the LeetCode challenges in easy and hard mode at the\nsame time."}),"\n",(0,i.jsxs)(t.ul,{children:["\n",(0,i.jsxs)(t.li,{children:["Link to the problem: ",(0,i.jsx)(t.a,{href:"https://leetcode.com/problems/sort-the-matrix-diagonally/",children:"https://leetcode.com/problems/sort-the-matrix-diagonally/"})]}),"\n"]}),"\n",(0,i.jsx)(t.h2,{id:"problem-description",children:"Problem description"}),"\n",(0,i.jsxs)(t.p,{children:["A ",(0,i.jsx)(t.strong,{children:"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 ",(0,i.jsx)(t.strong,{children:"matrix diagonal"})," starting\nfrom ",(0,i.jsx)(t.code,{children:"mat[2][0]"}),", where ",(0,i.jsx)(t.code,{children:"mat"})," is a ",(0,i.jsx)(t.code,{children:"6 x 3"})," matrix, includes cells ",(0,i.jsx)(t.code,{children:"mat[2][0]"}),",\n",(0,i.jsx)(t.code,{children:"mat[3][1]"}),", and ",(0,i.jsx)(t.code,{children:"mat[4][2]"}),"."]}),"\n",(0,i.jsxs)(t.p,{children:["Given an ",(0,i.jsx)(t.code,{children:"m x n"})," matrix ",(0,i.jsx)(t.code,{children:"mat"})," of integers, sort each matrix diagonal in ascending\norder and return the resulting matrix."]}),"\n",(0,i.jsx)(t.h3,{id:"example",children:"Example"}),"\n",(0,i.jsx)(t.p,{children:(0,i.jsx)(t.img,{src:"https://assets.leetcode.com/uploads/2020/01/21/1482_example_1_2.png",alt:"Image describing the problem"})}),"\n",(0,i.jsx)(t.h2,{id:"skeleton-and-initial-adjustments",children:"Skeleton and initial adjustments"}),"\n",(0,i.jsx)(t.p,{children:"We are given the following skeleton for the C++ and the given challenge:"}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-cpp",children:"class Solution {\npublic:\n vector> diagonalSort(vector>& mat) {\n \n }\n};\n"})}),"\n",(0,i.jsxs)(t.p,{children:["The 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 ",(0,i.jsx)(t.code,{children:"vector"})," header and using\nfully-qualified namespaces",(0,i.jsx)(t.sup,{children:(0,i.jsx)(t.a,{href:"#user-content-fn-1-b611be",id:"user-content-fnref-1-b611be","data-footnote-ref":!0,"aria-describedby":"footnote-label",children:"1"})})," and also adding few tests:"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-cpp",children:"#include \n#include \n\nusing matrix = std::vector>;\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",(0,i.jsx)(t.p,{children:"We 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",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-diff",children:"- matrix diagonalSort(matrix& mat)\n+ matrix diagonalSort(matrix mat)\n {\n+ return mat;\n }\n"})}),"\n",(0,i.jsx)(t.p,{children:"Now, we get the copy and we're good to go."}),"\n",(0,i.jsx)(t.h2,{id:"na\xefve-solution",children:"Na\xefve solution"}),"\n",(0,i.jsx)(t.p,{children:"As 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",(0,i.jsxs)(t.p,{children:["What does that mean for us? Well, we have an ",(0,i.jsx)(t.code,{children:"std::sort"}),", we can use it, right?\nLet's have a look at it:"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-cpp",children:"template< class RandomIt >\nvoid sort( RandomIt first, RandomIt last );\n"})}),"\n",(0,i.jsxs)(t.p,{children:["This overload is more than we need. What does it do? It just sorts the elements\nin the range ",(0,i.jsx)(t.code,{children:"[first, last)"})," using ",(0,i.jsx)(t.code,{children:"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",(0,i.jsxs)(t.p,{children:["What is the ",(0,i.jsx)(t.code,{children:"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 ",(0,i.jsx)(t.em,{children:"random access"}),"\n",(0,i.jsx)(t.em,{children:"iterator"})," and allows swapping its values at the same time."]}),"\n",(0,i.jsxs)(t.admonition,{title:"Random access iterator",type:"tip",children:[(0,i.jsxs)(t.p,{children:["What is the ",(0,i.jsx)(t.em,{children:"random access iterator"})," though? We can find it in a documentation\nand see the following description:"]}),(0,i.jsxs)(t.blockquote,{children:["\n",(0,i.jsxs)(t.p,{children:["A ",(0,i.jsx)(t.strong,{children:"LegacyRandomAccessIterator"})," is a ",(0,i.jsx)(t.a,{href:"https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator",children:"LegacyBidirectionalIterator"}),"\nthat can be moved to point to any element in constant time."]}),"\n"]}),(0,i.jsxs)(t.p,{children:["After 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",(0,i.jsx)(t.em,{children:"compiler-assisted development"}),"\u201d",(0,i.jsx)(t.sup,{children:(0,i.jsx)(t.a,{href:"#user-content-fn-2-b611be",id:"user-content-fnref-2-b611be","data-footnote-ref":!0,"aria-describedby":"footnote-label",children:"2"})})," if you will ;)"]})]}),"\n",(0,i.jsxs)(t.p,{children:["Now we know that we can use ",(0,i.jsx)(t.code,{children:"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",(0,i.jsx)(t.sup,{children:(0,i.jsx)(t.a,{href:"#user-content-fn-3-b611be",id:"user-content-fnref-3-b611be","data-footnote-ref":!0,"aria-describedby":"footnote-label",children:"3"})}),". And that way we get"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-cpp",children:"matrix 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",(0,i.jsx)(t.p,{children:"This solution looks very simple, doesn't it? Well, cause it is.\nLet's try compiling it:"}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{children:"matrix-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",(0,i.jsxs)(t.p,{children:["OK, seems about right. We haven't implemented the ",(0,i.jsx)(t.code,{children:"diagonals"})," yet. And based on\nwhat we've written so far, we need a function or a class ",(0,i.jsx)(t.code,{children:"diagonals"})," that will\ngive us the diagonals we need."]}),"\n",(0,i.jsxs)(t.h2,{id:"implementing-the-diagonals",children:["Implementing the ",(0,i.jsx)(t.code,{children:"diagonals"})]}),"\n",(0,i.jsxs)(t.p,{children:["Cool, so we need the function that will let us go through each and every diagonal\nin our matrix. We use the ",(0,i.jsx)(t.em,{children:"for-range"})," loop, so whatever we get back from the\n",(0,i.jsx)(t.code,{children:"diagonals"})," must support ",(0,i.jsx)(t.code,{children:".begin()"})," and ",(0,i.jsx)(t.code,{children:".end()"}),". Since I am a masochist, we will\ndo such functionality for a matrix of any type, not just the ",(0,i.jsx)(t.code,{children:"int"})," from the challenge."]}),"\n",(0,i.jsx)(t.p,{children:"As I said, we need to be able to"}),"\n",(0,i.jsxs)(t.ul,{children:["\n",(0,i.jsx)(t.li,{children:"construct the object"}),"\n",(0,i.jsx)(t.li,{children:"get the beginning"}),"\n",(0,i.jsx)(t.li,{children:"get the end (the \u201csentinel\u201d)"}),"\n"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-cpp",children:"template \nclass diagonals {\n using matrix_t = std::vector>;\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",(0,i.jsxs)(t.p,{children:["Now we have a ",(0,i.jsx)(t.code,{children:"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",(0,i.jsxs)(t.p,{children:["We have a templated class with templated ",(0,i.jsx)(t.code,{children:"T"})," that is used as a placeholder for any\ntype we would store in the matrix. Because I'm lazy, I have defined the ",(0,i.jsx)(t.code,{children:"matrix_t"}),"\ntype that is a \u201cshortcut\u201d for ",(0,i.jsx)(t.code,{children:"std::vector>"}),", 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 ",(0,i.jsx)(t.em,{children:"for-range"}),"."]}),"\n",(0,i.jsx)(t.h3,{id:"iterating-over-diagonals",children:"Iterating over diagonals"}),"\n",(0,i.jsxs)(t.p,{children:["Now 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,i.jsx)(t.code,{children:"(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",(0,i.jsx)(t.p,{children:"We 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",(0,i.jsxs)(t.p,{children:["We will start by updating the ",(0,i.jsx)(t.code,{children:"begin"})," and ",(0,i.jsx)(t.code,{children:"end"})," to reflect our choice accordingly."]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-cpp",children:"diagonals_iter begin() { return diagonals_iter { _matrix, 0, 0 }; }\ndiagonals_iter end() { return diagonals_iter { _matrix, 0, _matrix.size() }; }\n"})}),"\n",(0,i.jsxs)(t.p,{children:["For the ",(0,i.jsx)(t.code,{children:"begin"})," we return the first diagonal that starts at ",(0,i.jsx)(t.code,{children:"(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,i.jsx)(t.code,{children:"(0, height)"}),". Apart from the\nindices, we also need to pass reference to the matrix itself."]}),"\n",(0,i.jsx)(t.admonition,{type:"note",children:(0,i.jsxs)(t.p,{children:["You may have noticed that we also include the diagonals that have length 1,\nspecifically the ones at ",(0,i.jsx)(t.code,{children:"(0, height - 1)"})," and ",(0,i.jsx)(t.code,{children:"(width - 1, 0)"}),". We are implementing\nan iterator that ",(0,i.jsx)(t.strong,{children:"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",(0,i.jsxs)(t.p,{children:["Cool, let's leave the iterator itself to someone else, right?",(0,i.jsx)(t.sup,{children:(0,i.jsx)(t.a,{href:"#user-content-fn-4-b611be",id:"user-content-fnref-4-b611be","data-footnote-ref":!0,"aria-describedby":"footnote-label",children:"4"})})]}),"\n",(0,i.jsx)(t.h3,{id:"implementing-the-iterator-over-diagonals",children:"Implementing the iterator over diagonals"}),"\n",(0,i.jsxs)(t.p,{children:["We can start with a simple skeleton based on the information that we pass from\nthe ",(0,i.jsx)(t.code,{children:"diagonals"}),". Also to utilize the ",(0,i.jsx)(t.code,{children:"matrix_t"})," and also contain implementation\ndetails hidden away, we will put this code into the ",(0,i.jsx)(t.code,{children:"diagonals"})," class."]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-cpp",children:"class 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",(0,i.jsx)(t.p,{children:"In 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",(0,i.jsxs)(t.ul,{children:["\n",(0,i.jsx)(t.li,{children:"inequality operator (we need to know when we reach the end and have nothing to\niterate over)"}),"\n",(0,i.jsx)(t.li,{children:"preincrementation operator (we need to be able to move around the iterable)"}),"\n",(0,i.jsx)(t.li,{children:"dereference operator (we need to be able to retrieve the objects we iterate\nover)"}),"\n"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-cpp",children:"class 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 operator*() const { return diagonal { m, x, y }; }\n};\n"})}),"\n",(0,i.jsx)(t.p,{children:"Let'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",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-diff",children:"- return m != rhs.m || x != rhs.x || y != rhs.y;\n+ return x != rhs.x || y != rhs.y || m != rhs.m;\n"})}),"\n",(0,i.jsx)(t.p,{children:"Preincrementation is where the magic happens. If you have a better look, you can\nsee two branches of this operation:"}),"\n",(0,i.jsxs)(t.ol,{children:["\n",(0,i.jsxs)(t.li,{children:["When ",(0,i.jsx)(t.code,{children:"y != 0"})," (we're iterating over the diagonals in the first column)\nIn this case, we just bump the row and we're done."]}),"\n",(0,i.jsxs)(t.li,{children:["When ",(0,i.jsx)(t.code,{children:"y == 0"})," (we're iterating over the diagonals in the first row)\nIn this case, we bump the column and check if we haven't gotten out of bounds,\ni.e. the end of the first row. If we get out of the bounds, we're continuing\nwith the second diagonal in the first column."]}),"\n"]}),"\n",(0,i.jsxs)(t.p,{children:["Dereferencing 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 ",(0,i.jsx)(t.code,{children:"diagonal"}),"."]}),"\n",(0,i.jsxs)(t.h2,{id:"implementing-the-diagonal-itself",children:["Implementing the ",(0,i.jsx)(t.code,{children:"diagonal"})," itself"]}),"\n",(0,i.jsxs)(t.p,{children:["After 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 ",(0,i.jsx)(t.code,{children:"std::sort"}),"\nfunction. We can start with the following skeleton:"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-cpp",children:"template \nclass diagonal {\n using matrix_t = std::vector>;\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",(0,i.jsxs)(t.p,{children:["Initialization is rather simple, we just \u201ckeep\u201d the stuff we get, ",(0,i.jsx)(t.code,{children:"begin"})," is the\nsimplest, we just delegate."]}),"\n",(0,i.jsxs)(t.p,{children:["In case of the ",(0,i.jsx)(t.code,{children:"end"}),", it gets more complicated. We need to know where is the \u201cend\u201d\nof the diagonal. Since ",(0,i.jsx)(t.code,{children:"end"})," should point to the first element \u201cafter\u201d the iterable,\nwe know that it's the first position of the iterator where either ",(0,i.jsx)(t.code,{children:"y"})," becomes\n",(0,i.jsx)(t.code,{children:"matrix.size()"})," or ",(0,i.jsx)(t.code,{children:"x"})," becomes ",(0,i.jsx)(t.code,{children:"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 ",(0,i.jsx)(t.code,{children:"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",(0,i.jsx)(t.p,{children:"Now we just need to finish the iterator for the diagonal itself and we're done."}),"\n",(0,i.jsxs)(t.h3,{id:"implementing-diagonal_iter",children:["Implementing ",(0,i.jsx)(t.code,{children:"diagonal_iter"})]}),"\n",(0,i.jsxs)(t.p,{children:["This part is the hardest from all we need to do. It's because of the requirements\nof the ",(0,i.jsx)(t.code,{children:"std::sort"})," that requires us to implement a ",(0,i.jsx)(t.em,{children:"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",(0,i.jsxs)(t.p,{children:["Let's go through all of the functionality that our iterator needs to support to\nbe used in ",(0,i.jsx)(t.code,{children:"std::sort"}),". We need the usual operations like:"]}),"\n",(0,i.jsxs)(t.ul,{children:["\n",(0,i.jsx)(t.li,{children:"equality/inequality"}),"\n",(0,i.jsx)(t.li,{children:"incrementation"}),"\n",(0,i.jsx)(t.li,{children:"dereferencing"}),"\n"]}),"\n",(0,i.jsx)(t.p,{children:"We will also add all the types that our iterator uses with the category of the\niterator, i.e. what interface it supports:"}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-cpp",children:"class 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",(0,i.jsxs)(t.p,{children:["This is pretty similar to the previous iterator, but now we need to implement the\nremaining requirements of the ",(0,i.jsx)(t.em,{children:"random access iterator"}),". Let's see what those are:"]}),"\n",(0,i.jsxs)(t.ul,{children:["\n",(0,i.jsxs)(t.li,{children:["decrementation - cause we need to be able to move backwards too, since _random _\n",(0,i.jsx)(t.em,{children:"access iterator"})," extends the interface of ",(0,i.jsx)(t.em,{children:"bidirectional iterator"})]}),"\n",(0,i.jsx)(t.li,{children:"moving the iterator in either direction by steps given as an integer"}),"\n",(0,i.jsx)(t.li,{children:"being able to tell the distance between two iterators"}),"\n",(0,i.jsx)(t.li,{children:"define an ordering on the iterators"}),"\n"]}),"\n",(0,i.jsx)(t.p,{children:"Let's fill them in:"}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-cpp",children:"class 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",(0,i.jsx)(t.p,{children:"At 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",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{children:"/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1792:11: error: object of type 'diagonal::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_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_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_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_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_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::matrix_t &' (aka 'vector> &')\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_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_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_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_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::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::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_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_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_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::matrix_t &' (aka 'vector> &')\n matrix_t& m;\n ^\n"})}),"\n",(0,i.jsx)(t.p,{children:"That's a lot of noise, isn't it? Let's focus on the important parts:"}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{children:"/usr/bin/../lib/gcc/x86_64-redhat-linux/12/../../../../include/c++/12/bits/stl_algo.h:1792:11: error: object of type 'diagonal::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::matrix_t &' (aka 'vector> &')\n matrix_t& m;\n ^\n"})}),"\n",(0,i.jsx)(t.p,{children:"Ah! 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",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-diff",children:"# we need to keep a different type than reference\n- matrix_t& m;\n+ std::reference_wrapper 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",(0,i.jsxs)(t.p,{children:["We're done now! We have written an iterator over diagonals for a 2D ",(0,i.jsx)(t.code,{children:"vector"}),". You can have a look at the final result ",(0,i.jsx)(t.a,{href:"pathname:///files/blog/leetcode/sort-matrix-diagonally/matrix-sort.cpp",children:"here"}),"."]}),"\n",(0,i.jsxs)(t.section,{"data-footnotes":!0,className:"footnotes",children:[(0,i.jsx)(t.h2,{className:"sr-only",id:"footnote-label",children:"Footnotes"}),"\n",(0,i.jsxs)(t.ol,{children:["\n",(0,i.jsxs)(t.li,{id:"user-content-fn-1-b611be",children:["\n",(0,i.jsxs)(t.p,{children:["just because I'm used to it and don't care about your opinion ;) ",(0,i.jsx)(t.a,{href:"#user-content-fnref-1-b611be","data-footnote-backref":"","aria-label":"Back to reference 1",className:"data-footnote-backref",children:"\u21a9"})]}),"\n"]}),"\n",(0,i.jsxs)(t.li,{id:"user-content-fn-2-b611be",children:["\n",(0,i.jsxs)(t.p,{children:["exercise at your own risk ",(0,i.jsx)(t.a,{href:"#user-content-fnref-2-b611be","data-footnote-backref":"","aria-label":"Back to reference 2",className:"data-footnote-backref",children:"\u21a9"})]}),"\n"]}),"\n",(0,i.jsxs)(t.li,{id:"user-content-fn-3-b611be",children:["\n",(0,i.jsxs)(t.p,{children:["me in 5 minutes in fact, but don't make me scared ",(0,i.jsx)(t.a,{href:"#user-content-fnref-3-b611be","data-footnote-backref":"","aria-label":"Back to reference 3",className:"data-footnote-backref",children:"\u21a9"})]}),"\n"]}),"\n",(0,i.jsxs)(t.li,{id:"user-content-fn-4-b611be",children:["\n",(0,i.jsxs)(t.p,{children:["me in the next section\u2026 ",(0,i.jsx)(t.a,{href:"#user-content-fnref-4-b611be","data-footnote-backref":"","aria-label":"Back to reference 4",className:"data-footnote-backref",children:"\u21a9"})]}),"\n"]}),"\n"]}),"\n"]})]})}function h(e={}){const{wrapper:t}={...(0,a.a)(),...e.components};return t?(0,i.jsx)(t,{...e,children:(0,i.jsx)(c,{...e})}):c(e)}},11151:(e,t,n)=>{n.d(t,{Z:()=>s,a:()=>r});var i=n(67294);const a={},o=i.createContext(a);function r(e){const t=i.useContext(o);return i.useMemo((function(){return"function"==typeof e?e(t):{...t,...e}}),[t,e])}function s(e){let t;return t=e.disableParentContext?"function"==typeof e.components?e.components(a):e.components||a:r(e.components),i.createElement(o.Provider,{value:t},e.children)}}}]); \ No newline at end of file diff --git a/assets/js/d05e838c.3caaf7e6.js b/assets/js/d05e838c.c79b079a.js similarity index 98% rename from assets/js/d05e838c.3caaf7e6.js rename to assets/js/d05e838c.c79b079a.js index 0a36be3..c2e8fd8 100644 --- a/assets/js/d05e838c.3caaf7e6.js +++ b/assets/js/d05e838c.c79b079a.js @@ -1 +1 @@ -"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[6544],{63004:(e,n,r)=>{r.r(n),r.d(n,{assets:()=>d,contentTitle:()=>c,default:()=>a,frontMatter:()=>i,metadata:()=>o,toc:()=>l});var s=r(85893),t=r(11151);const i={id:"seminar-05-06",title:"5th and 6th seminar",description:"200IQ encryption.\n"},c=void 0,o={id:"bonuses/seminar-05-06",title:"5th and 6th seminar",description:"200IQ encryption.\n",source:"@site/c/bonuses/05-06.md",sourceDirName:"bonuses",slug:"/bonuses/seminar-05-06",permalink:"/c/bonuses/seminar-05-06",draft:!1,unlisted:!1,editUrl:"https://github.com/mfocko/blog/tree/main/c/bonuses/05-06.md",tags:[],version:"current",lastUpdatedAt:1704291155,formattedLastUpdatedAt:"Jan 3, 2024",frontMatter:{id:"seminar-05-06",title:"5th and 6th seminar",description:"200IQ encryption.\n"},sidebar:"autogeneratedBar",previous:{title:"4th seminar",permalink:"/c/bonuses/seminar-04"},next:{title:"8th seminar",permalink:"/c/bonuses/seminar-08"}},d={},l=[{value:"Introduction",id:"introduction",level:2},{value:"Task no. 1: Reverse (0.5 K\u20a1)",id:"task-no-1-reverse-05-k",level:3},{value:"Task no. 2: Vigen\xe8re (0.5 K\u20a1)",id:"task-no-2-vigen\xe8re-05-k",level:3},{value:"Bonus part (0.5 K\u20a1)",id:"bonus-part-05-k",level:4},{value:"Task no. 3: Bit madness (0.5 K\u20a1)",id:"task-no-3-bit-madness-05-k",level:3},{value:"Task no. 4: All combined to BMP (0.5 K\u20a1)",id:"task-no-4-all-combined-to-bmp-05-k",level:3},{value:"Submitting",id:"submitting",level:2}];function h(e){const n={a:"a",code:"code",h2:"h2",h3:"h3",h4:"h4",hr:"hr",li:"li",ol:"ol",p:"p",pre:"pre",ul:"ul",...(0,t.a)(),...e.components};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(n.p,{children:"For this bonus you can get at maximum 2.5 K\u20a1."}),"\n",(0,s.jsx)(n.p,{children:(0,s.jsx)(n.a,{href:"pathname:///files/c/bonuses/05-06.tar.gz",children:"Source"})}),"\n",(0,s.jsx)(n.h2,{id:"introduction",children:"Introduction"}),"\n",(0,s.jsx)(n.p,{children:"In this bonus you will implement few functions that will be used together for\nimplementing a very special cipher."}),"\n",(0,s.jsx)(n.h3,{id:"task-no-1-reverse-05-k",children:"Task no. 1: Reverse (0.5 K\u20a1)"}),"\n",(0,s.jsxs)(n.p,{children:["Write a function ",(0,s.jsx)(n.code,{children:"char* reverse(const char* text)"})," that returns copy of the input\nstring in reversed order (also uppercase)."]}),"\n",(0,s.jsxs)(n.p,{children:["In case you are given ",(0,s.jsx)(n.code,{children:"NULL"}),", return ",(0,s.jsx)(n.code,{children:"NULL"}),"."]}),"\n",(0,s.jsx)(n.p,{children:"Example (more in tests):"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-c",children:'char* reversed = reverse("Hello world!");\n\nprintf("%s\\n", reversed);\n// "!DLROW OLLEH"\n\nif (reversed != NULL) {\n free(reversed);\n}\n'})}),"\n",(0,s.jsx)(n.h3,{id:"task-no-2-vigen\xe8re-05-k",children:"Task no. 2: Vigen\xe8re (0.5 K\u20a1)"}),"\n",(0,s.jsx)(n.p,{children:"Vigen\xe8re cipher is similar to the Caesar cipher, but you also have a key that is\nused for encrypting (or decrypting)."}),"\n",(0,s.jsx)(n.p,{children:"Your task is to write two functions:"}),"\n",(0,s.jsxs)(n.ul,{children:["\n",(0,s.jsxs)(n.li,{children:[(0,s.jsx)(n.code,{children:"char* vigenere_encrypt(const char* key, const char* text)"})," for encrypting"]}),"\n",(0,s.jsxs)(n.li,{children:[(0,s.jsx)(n.code,{children:"char* vigenere_decrypt(const char* key, const char* text)"})," for decrypting"]}),"\n"]}),"\n",(0,s.jsx)(n.p,{children:"In both of those you should return uppercase characters."}),"\n",(0,s.jsx)(n.p,{children:"Meaning of the parameters you are given:"}),"\n",(0,s.jsxs)(n.ul,{children:["\n",(0,s.jsxs)(n.li,{children:[(0,s.jsx)(n.code,{children:"key"})," - String that represents key that is used for *crypting. It consists of\none word and can have only characters of the alphabet. Does not matter if they\nare uppercase or lowercase."]}),"\n",(0,s.jsxs)(n.li,{children:[(0,s.jsx)(n.code,{children:"text"})," - String that is to be *crypted."]}),"\n"]}),"\n",(0,s.jsxs)(n.p,{children:["Function returns address of the encrypted (or decrypted) string. Or ",(0,s.jsx)(n.code,{children:"NULL"})," in case\nerror occurs."]}),"\n",(0,s.jsx)(n.p,{children:"Example:"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-c",children:'char *encrypted = vigenere_encrypt("CoMPuTeR", "Hello world!");\n\nprintf("%s\\n", encrypted);\n// "JSXAI PSINR!"\n\nif (encrypted != NULL) {\n free(encrypted)\n}\n'})}),"\n",(0,s.jsx)(n.h4,{id:"bonus-part-05-k",children:"Bonus part (0.5 K\u20a1)"}),"\n",(0,s.jsx)(n.p,{children:"If you can utilize helper function that would do both encrypting and decrypting,\nyou can gain 0.5 K\u20a1."}),"\n",(0,s.jsxs)(n.p,{children:["Usage of ",(0,s.jsx)(n.code,{children:"true"}),"/",(0,s.jsx)(n.code,{children:"false"})," to decide path in code is prohibited. It leads to merging\nof both functions into one. Point of this part is to discover a way to do this\ngenerically in such way that there are no separate paths for one or the other. One\nfunction with no branching for both of them, parametrization is your friend :)"]}),"\n",(0,s.jsx)(n.h3,{id:"task-no-3-bit-madness-05-k",children:"Task no. 3: Bit madness (0.5 K\u20a1)"}),"\n",(0,s.jsx)(n.p,{children:"This is a state of the art crypto. Please do not share :)"}),"\n",(0,s.jsx)(n.p,{children:"For encrypting:"}),"\n",(0,s.jsxs)(n.ol,{children:["\n",(0,s.jsx)(n.li,{children:"Split the character that is to be encrypted in halves (4 and 4 bits each)."}),"\n",(0,s.jsx)(n.li,{children:"Bits in 1st half are to be split into pairs. Swap bits in those pairs."}),"\n",(0,s.jsxs)(n.li,{children:["Then use the 4 bits that you created in the 2nd step for ",(0,s.jsx)(n.code,{children:"XOR"})," with the other\n4 bits."]}),"\n"]}),"\n",(0,s.jsxs)(n.p,{children:["This simple and ingenious principle will be illustrated on the following example.\nString we want to encrypt is ",(0,s.jsx)(n.code,{children:"Hello world!"}),". We need to encrypt each letter separately,\nso we will demonstrate on letter ",(0,s.jsx)(n.code,{children:"H"}),":"]}),"\n",(0,s.jsxs)(n.ol,{children:["\n",(0,s.jsxs)(n.li,{children:["\n",(0,s.jsxs)(n.p,{children:["Letter ",(0,s.jsx)(n.code,{children:"H"})," is represented in ASCII as ",(0,s.jsx)(n.code,{children:"72"}),"."]}),"\n",(0,s.jsxs)(n.p,{children:[(0,s.jsx)(n.code,{children:"72"})," represented in binary is: ",(0,s.jsx)(n.code,{children:"01001000"}),". So first 4 bits are: ",(0,s.jsx)(n.code,{children:"0100"})," and last\n4 bits are ",(0,s.jsx)(n.code,{children:"1000"}),"."]}),"\n"]}),"\n",(0,s.jsxs)(n.li,{children:["\n",(0,s.jsxs)(n.p,{children:["First half of bits (",(0,s.jsx)(n.code,{children:"0100"}),") consists of 2 pairs (",(0,s.jsx)(n.code,{children:"01"})," and ",(0,s.jsx)(n.code,{children:"00"}),") which we swap\n(",(0,s.jsx)(n.code,{children:"01 ~> 10"})," and ",(0,s.jsx)(n.code,{children:"00 ~> 00"}),"). That way we get ",(0,s.jsx)(n.code,{children:"1000"}),"."]}),"\n"]}),"\n",(0,s.jsxs)(n.li,{children:["\n",(0,s.jsx)(n.p,{children:"That half is used for xor with the other 4 bits:"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{children:" 1000 // second half\nXOR 1000 // first half after 2nd step\n--------\n 0000\n"})}),"\n"]}),"\n",(0,s.jsxs)(n.li,{children:["\n",(0,s.jsxs)(n.p,{children:["Now we combine both halves (first one is ",(0,s.jsx)(n.code,{children:"1000"}),", which we got from the 2nd step\nand second one is ",(0,s.jsx)(n.code,{children:"0000"}),", which we got from the 3rd step) and get ",(0,s.jsx)(n.code,{children:"10000000"}),",\nwhich is encrypted character ",(0,s.jsx)(n.code,{children:"H"})," using this method."]}),"\n"]}),"\n"]}),"\n",(0,s.jsx)(n.p,{children:"In case of decryption, reverse those steps."}),"\n",(0,s.jsx)(n.p,{children:"Your task is to implement functions:"}),"\n",(0,s.jsxs)(n.ul,{children:["\n",(0,s.jsx)(n.li,{children:(0,s.jsx)(n.code,{children:"unsigned char* bit_encrypt(const char* text)"})}),"\n",(0,s.jsx)(n.li,{children:(0,s.jsx)(n.code,{children:"char* bit_decrypt(const unsigned char* text)"})}),"\n"]}),"\n",(0,s.jsx)(n.p,{children:"Example:"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-c",children:'unsigned char* encrypted = bit_encrypt("Hello world!");\n\nfor (int i = 0; i < 12;i++) {\n printf("%x ", encrypted[i]);\n //80 9c 95 95 96 11 bc 96 b9 95 9d 10\n}\n\nif (encrypted != NULL) {\n free(encrypted);\n}\n'})}),"\n",(0,s.jsx)(n.h3,{id:"task-no-4-all-combined-to-bmp-05-k",children:"Task no. 4: All combined to BMP (0.5 K\u20a1)"}),"\n",(0,s.jsx)(n.p,{children:"Authors of the BMP cipher are non-disclosed :)"}),"\n",(0,s.jsx)(n.p,{children:"Create pair of functions:"}),"\n",(0,s.jsxs)(n.ul,{children:["\n",(0,s.jsx)(n.li,{children:(0,s.jsx)(n.code,{children:"unsigned char* bmp_encrypt(const char* key, const char* text)"})}),"\n",(0,s.jsx)(n.li,{children:(0,s.jsx)(n.code,{children:"char* bmp_decrypt(const char* key, const unsigned char* text)"})}),"\n"]}),"\n",(0,s.jsx)(n.p,{children:"BMP cipher consists of following steps for encrypting:"}),"\n",(0,s.jsxs)(n.ol,{children:["\n",(0,s.jsx)(n.li,{children:"Reverse the input string"}),"\n",(0,s.jsx)(n.li,{children:"Use Vigenere on the string you got from step #1"}),"\n",(0,s.jsx)(n.li,{children:"Use bit madness on the string you got from step #2"}),"\n"]}),"\n",(0,s.jsx)(n.p,{children:"For decrypting, reverse the steps."}),"\n",(0,s.jsx)(n.h2,{id:"submitting",children:"Submitting"}),"\n",(0,s.jsx)(n.p,{children:"In case you have any questions, feel free to reach out to me."}),"\n",(0,s.jsx)(n.hr,{})]})}function a(e={}){const{wrapper:n}={...(0,t.a)(),...e.components};return n?(0,s.jsx)(n,{...e,children:(0,s.jsx)(h,{...e})}):h(e)}},11151:(e,n,r)=>{r.d(n,{Z:()=>o,a:()=>c});var s=r(67294);const t={},i=s.createContext(t);function c(e){const n=s.useContext(i);return s.useMemo((function(){return"function"==typeof e?e(n):{...n,...e}}),[n,e])}function o(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(t):e.components||t:c(e.components),s.createElement(i.Provider,{value:n},e.children)}}}]); \ No newline at end of file +"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[6544],{63004:(e,n,r)=>{r.r(n),r.d(n,{assets:()=>d,contentTitle:()=>c,default:()=>a,frontMatter:()=>i,metadata:()=>o,toc:()=>l});var s=r(85893),t=r(11151);const i={id:"seminar-05-06",title:"5th and 6th seminar",description:"200IQ encryption.\n"},c=void 0,o={id:"bonuses/seminar-05-06",title:"5th and 6th seminar",description:"200IQ encryption.\n",source:"@site/c/bonuses/05-06.md",sourceDirName:"bonuses",slug:"/bonuses/seminar-05-06",permalink:"/c/bonuses/seminar-05-06",draft:!1,unlisted:!1,editUrl:"https://github.com/mfocko/blog/tree/main/c/bonuses/05-06.md",tags:[],version:"current",lastUpdatedAt:1704558496,formattedLastUpdatedAt:"Jan 6, 2024",frontMatter:{id:"seminar-05-06",title:"5th and 6th seminar",description:"200IQ encryption.\n"},sidebar:"autogeneratedBar",previous:{title:"4th seminar",permalink:"/c/bonuses/seminar-04"},next:{title:"8th seminar",permalink:"/c/bonuses/seminar-08"}},d={},l=[{value:"Introduction",id:"introduction",level:2},{value:"Task no. 1: Reverse (0.5 K\u20a1)",id:"task-no-1-reverse-05-k",level:3},{value:"Task no. 2: Vigen\xe8re (0.5 K\u20a1)",id:"task-no-2-vigen\xe8re-05-k",level:3},{value:"Bonus part (0.5 K\u20a1)",id:"bonus-part-05-k",level:4},{value:"Task no. 3: Bit madness (0.5 K\u20a1)",id:"task-no-3-bit-madness-05-k",level:3},{value:"Task no. 4: All combined to BMP (0.5 K\u20a1)",id:"task-no-4-all-combined-to-bmp-05-k",level:3},{value:"Submitting",id:"submitting",level:2}];function h(e){const n={a:"a",code:"code",h2:"h2",h3:"h3",h4:"h4",hr:"hr",li:"li",ol:"ol",p:"p",pre:"pre",ul:"ul",...(0,t.a)(),...e.components};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(n.p,{children:"For this bonus you can get at maximum 2.5 K\u20a1."}),"\n",(0,s.jsx)(n.p,{children:(0,s.jsx)(n.a,{href:"pathname:///files/c/bonuses/05-06.tar.gz",children:"Source"})}),"\n",(0,s.jsx)(n.h2,{id:"introduction",children:"Introduction"}),"\n",(0,s.jsx)(n.p,{children:"In this bonus you will implement few functions that will be used together for\nimplementing a very special cipher."}),"\n",(0,s.jsx)(n.h3,{id:"task-no-1-reverse-05-k",children:"Task no. 1: Reverse (0.5 K\u20a1)"}),"\n",(0,s.jsxs)(n.p,{children:["Write a function ",(0,s.jsx)(n.code,{children:"char* reverse(const char* text)"})," that returns copy of the input\nstring in reversed order (also uppercase)."]}),"\n",(0,s.jsxs)(n.p,{children:["In case you are given ",(0,s.jsx)(n.code,{children:"NULL"}),", return ",(0,s.jsx)(n.code,{children:"NULL"}),"."]}),"\n",(0,s.jsx)(n.p,{children:"Example (more in tests):"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-c",children:'char* reversed = reverse("Hello world!");\n\nprintf("%s\\n", reversed);\n// "!DLROW OLLEH"\n\nif (reversed != NULL) {\n free(reversed);\n}\n'})}),"\n",(0,s.jsx)(n.h3,{id:"task-no-2-vigen\xe8re-05-k",children:"Task no. 2: Vigen\xe8re (0.5 K\u20a1)"}),"\n",(0,s.jsx)(n.p,{children:"Vigen\xe8re cipher is similar to the Caesar cipher, but you also have a key that is\nused for encrypting (or decrypting)."}),"\n",(0,s.jsx)(n.p,{children:"Your task is to write two functions:"}),"\n",(0,s.jsxs)(n.ul,{children:["\n",(0,s.jsxs)(n.li,{children:[(0,s.jsx)(n.code,{children:"char* vigenere_encrypt(const char* key, const char* text)"})," for encrypting"]}),"\n",(0,s.jsxs)(n.li,{children:[(0,s.jsx)(n.code,{children:"char* vigenere_decrypt(const char* key, const char* text)"})," for decrypting"]}),"\n"]}),"\n",(0,s.jsx)(n.p,{children:"In both of those you should return uppercase characters."}),"\n",(0,s.jsx)(n.p,{children:"Meaning of the parameters you are given:"}),"\n",(0,s.jsxs)(n.ul,{children:["\n",(0,s.jsxs)(n.li,{children:[(0,s.jsx)(n.code,{children:"key"})," - String that represents key that is used for *crypting. It consists of\none word and can have only characters of the alphabet. Does not matter if they\nare uppercase or lowercase."]}),"\n",(0,s.jsxs)(n.li,{children:[(0,s.jsx)(n.code,{children:"text"})," - String that is to be *crypted."]}),"\n"]}),"\n",(0,s.jsxs)(n.p,{children:["Function returns address of the encrypted (or decrypted) string. Or ",(0,s.jsx)(n.code,{children:"NULL"})," in case\nerror occurs."]}),"\n",(0,s.jsx)(n.p,{children:"Example:"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-c",children:'char *encrypted = vigenere_encrypt("CoMPuTeR", "Hello world!");\n\nprintf("%s\\n", encrypted);\n// "JSXAI PSINR!"\n\nif (encrypted != NULL) {\n free(encrypted)\n}\n'})}),"\n",(0,s.jsx)(n.h4,{id:"bonus-part-05-k",children:"Bonus part (0.5 K\u20a1)"}),"\n",(0,s.jsx)(n.p,{children:"If you can utilize helper function that would do both encrypting and decrypting,\nyou can gain 0.5 K\u20a1."}),"\n",(0,s.jsxs)(n.p,{children:["Usage of ",(0,s.jsx)(n.code,{children:"true"}),"/",(0,s.jsx)(n.code,{children:"false"})," to decide path in code is prohibited. It leads to merging\nof both functions into one. Point of this part is to discover a way to do this\ngenerically in such way that there are no separate paths for one or the other. One\nfunction with no branching for both of them, parametrization is your friend :)"]}),"\n",(0,s.jsx)(n.h3,{id:"task-no-3-bit-madness-05-k",children:"Task no. 3: Bit madness (0.5 K\u20a1)"}),"\n",(0,s.jsx)(n.p,{children:"This is a state of the art crypto. Please do not share :)"}),"\n",(0,s.jsx)(n.p,{children:"For encrypting:"}),"\n",(0,s.jsxs)(n.ol,{children:["\n",(0,s.jsx)(n.li,{children:"Split the character that is to be encrypted in halves (4 and 4 bits each)."}),"\n",(0,s.jsx)(n.li,{children:"Bits in 1st half are to be split into pairs. Swap bits in those pairs."}),"\n",(0,s.jsxs)(n.li,{children:["Then use the 4 bits that you created in the 2nd step for ",(0,s.jsx)(n.code,{children:"XOR"})," with the other\n4 bits."]}),"\n"]}),"\n",(0,s.jsxs)(n.p,{children:["This simple and ingenious principle will be illustrated on the following example.\nString we want to encrypt is ",(0,s.jsx)(n.code,{children:"Hello world!"}),". We need to encrypt each letter separately,\nso we will demonstrate on letter ",(0,s.jsx)(n.code,{children:"H"}),":"]}),"\n",(0,s.jsxs)(n.ol,{children:["\n",(0,s.jsxs)(n.li,{children:["\n",(0,s.jsxs)(n.p,{children:["Letter ",(0,s.jsx)(n.code,{children:"H"})," is represented in ASCII as ",(0,s.jsx)(n.code,{children:"72"}),"."]}),"\n",(0,s.jsxs)(n.p,{children:[(0,s.jsx)(n.code,{children:"72"})," represented in binary is: ",(0,s.jsx)(n.code,{children:"01001000"}),". So first 4 bits are: ",(0,s.jsx)(n.code,{children:"0100"})," and last\n4 bits are ",(0,s.jsx)(n.code,{children:"1000"}),"."]}),"\n"]}),"\n",(0,s.jsxs)(n.li,{children:["\n",(0,s.jsxs)(n.p,{children:["First half of bits (",(0,s.jsx)(n.code,{children:"0100"}),") consists of 2 pairs (",(0,s.jsx)(n.code,{children:"01"})," and ",(0,s.jsx)(n.code,{children:"00"}),") which we swap\n(",(0,s.jsx)(n.code,{children:"01 ~> 10"})," and ",(0,s.jsx)(n.code,{children:"00 ~> 00"}),"). That way we get ",(0,s.jsx)(n.code,{children:"1000"}),"."]}),"\n"]}),"\n",(0,s.jsxs)(n.li,{children:["\n",(0,s.jsx)(n.p,{children:"That half is used for xor with the other 4 bits:"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{children:" 1000 // second half\nXOR 1000 // first half after 2nd step\n--------\n 0000\n"})}),"\n"]}),"\n",(0,s.jsxs)(n.li,{children:["\n",(0,s.jsxs)(n.p,{children:["Now we combine both halves (first one is ",(0,s.jsx)(n.code,{children:"1000"}),", which we got from the 2nd step\nand second one is ",(0,s.jsx)(n.code,{children:"0000"}),", which we got from the 3rd step) and get ",(0,s.jsx)(n.code,{children:"10000000"}),",\nwhich is encrypted character ",(0,s.jsx)(n.code,{children:"H"})," using this method."]}),"\n"]}),"\n"]}),"\n",(0,s.jsx)(n.p,{children:"In case of decryption, reverse those steps."}),"\n",(0,s.jsx)(n.p,{children:"Your task is to implement functions:"}),"\n",(0,s.jsxs)(n.ul,{children:["\n",(0,s.jsx)(n.li,{children:(0,s.jsx)(n.code,{children:"unsigned char* bit_encrypt(const char* text)"})}),"\n",(0,s.jsx)(n.li,{children:(0,s.jsx)(n.code,{children:"char* bit_decrypt(const unsigned char* text)"})}),"\n"]}),"\n",(0,s.jsx)(n.p,{children:"Example:"}),"\n",(0,s.jsx)(n.pre,{children:(0,s.jsx)(n.code,{className:"language-c",children:'unsigned char* encrypted = bit_encrypt("Hello world!");\n\nfor (int i = 0; i < 12;i++) {\n printf("%x ", encrypted[i]);\n //80 9c 95 95 96 11 bc 96 b9 95 9d 10\n}\n\nif (encrypted != NULL) {\n free(encrypted);\n}\n'})}),"\n",(0,s.jsx)(n.h3,{id:"task-no-4-all-combined-to-bmp-05-k",children:"Task no. 4: All combined to BMP (0.5 K\u20a1)"}),"\n",(0,s.jsx)(n.p,{children:"Authors of the BMP cipher are non-disclosed :)"}),"\n",(0,s.jsx)(n.p,{children:"Create pair of functions:"}),"\n",(0,s.jsxs)(n.ul,{children:["\n",(0,s.jsx)(n.li,{children:(0,s.jsx)(n.code,{children:"unsigned char* bmp_encrypt(const char* key, const char* text)"})}),"\n",(0,s.jsx)(n.li,{children:(0,s.jsx)(n.code,{children:"char* bmp_decrypt(const char* key, const unsigned char* text)"})}),"\n"]}),"\n",(0,s.jsx)(n.p,{children:"BMP cipher consists of following steps for encrypting:"}),"\n",(0,s.jsxs)(n.ol,{children:["\n",(0,s.jsx)(n.li,{children:"Reverse the input string"}),"\n",(0,s.jsx)(n.li,{children:"Use Vigenere on the string you got from step #1"}),"\n",(0,s.jsx)(n.li,{children:"Use bit madness on the string you got from step #2"}),"\n"]}),"\n",(0,s.jsx)(n.p,{children:"For decrypting, reverse the steps."}),"\n",(0,s.jsx)(n.h2,{id:"submitting",children:"Submitting"}),"\n",(0,s.jsx)(n.p,{children:"In case you have any questions, feel free to reach out to me."}),"\n",(0,s.jsx)(n.hr,{})]})}function a(e={}){const{wrapper:n}={...(0,t.a)(),...e.components};return n?(0,s.jsx)(n,{...e,children:(0,s.jsx)(h,{...e})}):h(e)}},11151:(e,n,r)=>{r.d(n,{Z:()=>o,a:()=>c});var s=r(67294);const t={},i=s.createContext(t);function c(e){const n=s.useContext(i);return s.useMemo((function(){return"function"==typeof e?e(n):{...n,...e}}),[n,e])}function o(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(t):e.components||t:c(e.components),s.createElement(i.Provider,{value:n},e.children)}}}]); \ No newline at end of file diff --git a/assets/js/dff2ebad.2596a554.js b/assets/js/dff2ebad.26aca592.js similarity index 55% rename from assets/js/dff2ebad.2596a554.js rename to assets/js/dff2ebad.26aca592.js index 38783df..c26f033 100644 --- a/assets/js/dff2ebad.2596a554.js +++ b/assets/js/dff2ebad.26aca592.js @@ -1 +1 @@ -"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[146],{42492:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>r,contentTitle:()=>a,default:()=>h,frontMatter:()=>s,metadata:()=>l,toc:()=>c});var i=n(85893),o=n(11151);const s={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:!1},a=void 0,l={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:!0,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:!1},unlisted:!1,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"}},r={authorsImageUrls:[void 0]},c=[{value:"Day 1: Calorie Counting",id:"day-1-calorie-counting",level:2},{value:"Solution",id:"solution",level:3},{value:"Day 2: Rock Paper Scissors",id:"day-2-rock-paper-scissors",level:2},{value:"Solution",id:"solution-1",level:3},{value:"Day 3: Rucksack Reorganization",id:"day-3-rucksack-reorganization",level:2},{value:"Solution",id:"solution-2",level:3},{value:"Day 4: Camp Cleanup",id:"day-4-camp-cleanup",level:2},{value:"Solution",id:"solution-3",level:3},{value:"Day 5: Supply Stacks",id:"day-5-supply-stacks",level:2},{value:"Solution",id:"solution-4",level:3},{value:"Day 6: Tuning Trouble",id:"day-6-tuning-trouble",level:2},{value:"Solution",id:"solution-5",level:3},{value:"Day 7: No Space Left On Device",id:"day-7-no-space-left-on-device",level:2},{value:"Solution",id:"solution-6",level:3},{value:"Post Mortem",id:"post-mortem",level:2},{value:"Rc<T> vs Rc<RefCell<T>>",id:"rct-vs-rcrefcellt",level:3}];function d(e){const t={a:"a",admonition:"admonition",annotation:"annotation",blockquote:"blockquote",code:"code",del:"del",em:"em",h2:"h2",h3:"h3",li:"li",math:"math",mi:"mi",mrow:"mrow",p:"p",pre:"pre",semantics:"semantics",span:"span",strong:"strong",ul:"ul",...(0,o.a)(),...e.components};return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)(t.p,{children:["Let's go through the first week of ",(0,i.jsx)(t.a,{href:"https://adventofcode.com",children:(0,i.jsx)(t.em,{children:"Advent of Code"})})," in Rust."]}),"\n",(0,i.jsx)(t.admonition,{type:"note",children:(0,i.jsxs)(t.p,{children:["If you wish to have a look at the solutions, you can follow them on my ",(0,i.jsx)(t.a,{href:"https://gitlab.com/mfocko/advent-of-code-2022",children:"GitLab"}),".\nMore specifically in the ",(0,i.jsx)(t.a,{href:"https://gitlab.com/mfocko/advent-of-code-2022/-/tree/main/src/bin",children:(0,i.jsx)(t.code,{children:"/src/bin/"})}),"."]})}),"\n",(0,i.jsxs)(t.p,{children:["I will try to summarize my experience with using Rust for the AoC. Trying it out\nages ago, I believe it will be ",(0,i.jsx)(t.em,{children:"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 ","\ud83d\udc4d"," moments."]}),"\n",(0,i.jsx)(t.h2,{id:"day-1-calorie-counting",children:(0,i.jsx)(t.a,{href:"https://adventofcode.com/2022/day/1",children:"Day 1: Calorie Counting"})}),"\n",(0,i.jsx)(t.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(t.p,{children:"As 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",(0,i.jsxs)(t.blockquote,{children:["\n",(0,i.jsx)(t.p,{children:"Wakey wakey!"}),"\n"]}),"\n",(0,i.jsx)(t.p,{children:"Programming 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",(0,i.jsxs)(t.p,{children:["At first I've decided to put asserts into my ",(0,i.jsx)(t.code,{children:"main"}),", something like"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-rust",children:'assert_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",(0,i.jsx)(t.p,{children:"However, 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",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-rust",children:'#[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",(0,i.jsxs)(t.p,{children:["And later on I have noticed, it's hard to tell the difference between the days,\nso I further renamed the ",(0,i.jsx)(t.code,{children:"mod"})," from generic ",(0,i.jsx)(t.code,{children:"tests"})," to reflect the days."]}),"\n",(0,i.jsxs)(t.p,{children:["Also after finishing the first day puzzle, I have installed an ",(0,i.jsx)(t.a,{href:"https://github.com/mozilla/sccache",children:(0,i.jsx)(t.code,{children:"sccache"})})," to\ncache the builds, so that the build time is lower, cause it was kinda unbearable."]}),"\n",(0,i.jsx)(t.h3,{id:"solution",children:"Solution"}),"\n",(0,i.jsx)(t.p,{children:"Well, 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",(0,i.jsxs)(t.ul,{children:["\n",(0,i.jsx)(t.li,{children:"keep all the calories, sort them, take what we need"}),"\n",(0,i.jsx)(t.li,{children:"keep all the calories and use max heap"}),"\n",(0,i.jsx)(t.li,{children:"use min heap and maintain at most N calories that we need"}),"\n"]}),"\n",(0,i.jsx)(t.h2,{id:"day-2-rock-paper-scissors",children:(0,i.jsx)(t.a,{href:"https://adventofcode.com/2022/day/2",children:"Day 2: Rock Paper Scissors"})}),"\n",(0,i.jsx)(t.admonition,{title:"tl;dr",type:"info",children:(0,i.jsxs)(t.p,{children:["You want to know what score did you achieve while playing ",(0,i.jsx)(t.em,{children:"Rock Paper Scissors"}),".\nAnd then you want to be strategic about it."]})}),"\n",(0,i.jsx)(t.p,{children:"Apart from the technical details of the puzzle, it went relatively smooth."}),"\n",(0,i.jsx)(t.h3,{id:"solution-1",children:"Solution"}),"\n",(0,i.jsx)(t.p,{children:"I took relatively na\xefve approach and then tried to simplify it."}),"\n",(0,i.jsx)(t.h2,{id:"day-3-rucksack-reorganization",children:(0,i.jsx)(t.a,{href:"https://adventofcode.com/2022/day/3",children:"Day 3: Rucksack Reorganization"})}),"\n",(0,i.jsx)(t.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(t.p,{children:"Let'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",(0,i.jsx)(t.p,{children:"This 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",(0,i.jsx)(t.admonition,{title:"Fun fact",type:"tip",children:(0,i.jsx)(t.p,{children:"Fighting the compiler took me 30 minutes."})}),"\n",(0,i.jsx)(t.p,{children:"We 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",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-rust",children:"let top: HashSet = [1, 2, 3].iter().collect();\nlet bottom: HashSet = [3, 4, 5].iter().collect();\n"})}),"\n",(0,i.jsxs)(t.p,{children:["Now, the first issue that we encounter is caused by the fact that we are using\na slice (the ",(0,i.jsx)(t.code,{children:"[\u2026]"}),"), iterator of that returns ",(0,i.jsx)(t.strong,{children:"references"})," to the numbers.\nAnd we get immediately yelled at by the compiler, because the numbers are discarded\nafter running the ",(0,i.jsx)(t.code,{children:".collect"}),". To fix this, we can use ",(0,i.jsx)(t.code,{children:".into_iter"}),":"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-rust",children:"let top: HashSet = [1, 2, 3].into_iter().collect();\nlet bottom: HashSet = [3, 4, 5].into_iter().collect();\n"})}),"\n",(0,i.jsx)(t.p,{children:"This way the numbers will get copied instead of referenced. OK, let's find the\nintersection of those 2 collections:"}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-rust",children:'println!("Common elements: {:?}", top.intersection(&bottom));\n'})}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{children:"Common elements: [3]\n"})}),"\n",(0,i.jsx)(t.admonition,{type:"caution",children:(0,i.jsxs)(t.p,{children:["Notice that we need to do ",(0,i.jsx)(t.code,{children:"&bottom"}),". It explicitly specifies that ",(0,i.jsx)(t.code,{children:".intersection"}),"\n",(0,i.jsx)(t.strong,{children:"borrows"})," the ",(0,i.jsx)(t.code,{children:"bottom"}),", i.e. takes an immutable reference to it."]})}),"\n",(0,i.jsx)(t.p,{children:"That's what we want, right? Looks like it! \\o/"}),"\n",(0,i.jsx)(t.p,{children:"Next 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",(0,i.jsxs)(t.p,{children:["Let's have a look at the type of the ",(0,i.jsx)(t.code,{children:".intersection"})]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-rust",children:"pub fn intersection<'a>(\n\xa0\xa0\xa0\xa0&'a self,\n\xa0\xa0\xa0\xa0other: &'a HashSet\n) -> Intersection<'a, T, S>\n"})}),"\n",(0,i.jsx)(t.p,{children:"OK\u2026 Huh\u2026 But we have an example there!"}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-rust",children:"let intersection: HashSet<_> = a.intersection(&b).collect();\n"})}),"\n",(0,i.jsx)(t.p,{children:"Cool, that's all we need."}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-rust",children:'let top: HashSet = [1, 2, 3, 4].into_iter().collect();\nlet bottom: HashSet = [3, 4, 5, 6].into_iter().collect();\nlet top_2: HashSet = [2, 3, 4, 5, 6].into_iter().collect();\nlet bottom_2: HashSet = [4, 5, 6].into_iter().collect();\n\nlet intersection: HashSet<_> = top.intersection(&bottom).collect();\nprintln!("Intersection: {:?}", intersection);\n'})}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{children:"Intersection: {3, 4}\n"})}),"\n",(0,i.jsxs)(t.p,{children:["Cool, so let's do the intersection with the ",(0,i.jsx)(t.code,{children:"top_2"}),":"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-rust",children:'let top: HashSet = [1, 2, 3, 4].into_iter().collect();\nlet bottom: HashSet = [3, 4, 5, 6].into_iter().collect();\nlet top_2: HashSet = [2, 3, 4, 5, 6].into_iter().collect();\nlet bottom_2: HashSet = [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",(0,i.jsx)(t.p,{children:"And we get yelled at by the compiler:"}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{children:"error[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`\n"})}),"\n",(0,i.jsx)(t.p,{children:"/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",(0,i.jsx)(t.admonition,{type:"tip",children:(0,i.jsxs)(t.p,{children:["It 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 ",(0,i.jsx)(t.del,{children:"drilling your ass"})," having your back and\nmaking sure you're not doing something naughty that may cause an ",(0,i.jsx)(t.strong,{children:"undefined"}),"\n",(0,i.jsx)(t.strong,{children:"behavior"}),"."]})}),"\n",(0,i.jsxs)(t.p,{children:["To resolve this we need to get an iterator that ",(0,i.jsx)(t.strong,{children:"clones"})," the elements:"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-rust",children:'let top: HashSet = [1, 2, 3, 4].into_iter().collect();\nlet bottom: HashSet = [3, 4, 5, 6].into_iter().collect();\nlet top_2: HashSet = [2, 3, 4, 5, 6].into_iter().collect();\nlet bottom_2: HashSet = [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",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{children:"Intersection: {4}\n"})}),"\n",(0,i.jsx)(t.h3,{id:"solution-2",children:"Solution"}),"\n",(0,i.jsxs)(t.p,{children:["The approach is pretty simple, if you omit the ",(0,i.jsx)(t.em,{children:"1on1 with the compiler"}),". You just\nhave some fun with the set operations :)"]}),"\n",(0,i.jsx)(t.h2,{id:"day-4-camp-cleanup",children:(0,i.jsx)(t.a,{href:"https://adventofcode.com/2022/day/4",children:"Day 4: Camp Cleanup"})}),"\n",(0,i.jsx)(t.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(t.p,{children:"Elves are cleaning up the camp and they got overlapping sections to clean up.\nFind how many overlap and can take the day off."})}),"\n",(0,i.jsxs)(t.p,{children:[(0,i.jsx)(t.a,{href:"https://doc.rust-lang.org/std/ops/struct.RangeInclusive.html",children:(0,i.jsx)(t.code,{children:"RangeInclusive"})})," is your friend not an enemy :)"]}),"\n",(0,i.jsx)(t.h3,{id:"solution-3",children:"Solution"}),"\n",(0,i.jsxs)(t.p,{children:["Relatively easy, you just need to parse the input and know what you want. Rust's\n",(0,i.jsx)(t.code,{children:"RangeInclusive"})," type helped a lot, cause it took care of all abstractions."]}),"\n",(0,i.jsx)(t.h2,{id:"day-5-supply-stacks",children:(0,i.jsx)(t.a,{href:"https://adventofcode.com/2022/day/5",children:"Day 5: Supply Stacks"})}),"\n",(0,i.jsx)(t.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(t.p,{children:"Let's play with stacks of crates."})}),"\n",(0,i.jsx)(t.p,{children:"Very easy problem with very annoying input. You can judge yourself:"}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{children:" [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",(0,i.jsx)(t.p,{children:"Good luck transforming that into something reasonable :)"}),"\n",(0,i.jsx)(t.admonition,{title:"Fun fact",type:"tip",children:(0,i.jsx)(t.p,{children:"Took me 40 minutes to parse this reasonably, including fighting the compiler."})}),"\n",(0,i.jsx)(t.h3,{id:"solution-4",children:"Solution"}),"\n",(0,i.jsxs)(t.p,{children:["For the initial solution I went with a manual solution (as in ",(0,i.jsx)(t.em,{children:"I have done all"}),"\n",(0,i.jsx)(t.em,{children:"the work"}),". Later on I have decided to explore the ",(0,i.jsx)(t.code,{children:"std"})," and interface of the\n",(0,i.jsx)(t.code,{children:"std::vec::Vec"})," and found ",(0,i.jsx)(t.a,{href:"https://doc.rust-lang.org/std/vec/struct.Vec.html#method.split_off",children:(0,i.jsx)(t.code,{children:"split_off"})})," which takes an index and splits (duh)\nthe vector:"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-rust",children:"let mut vec = vec![1, 2, 3];\nlet vec2 = vec.split_off(1);\nassert_eq!(vec, [1]);\nassert_eq!(vec2, [2, 3]);\n"})}),"\n",(0,i.jsxs)(t.p,{children:["This helped me simplify my solution a lot and also get rid of some ",(0,i.jsx)(t.em,{children:"edge cases"}),"."]}),"\n",(0,i.jsx)(t.h2,{id:"day-6-tuning-trouble",children:(0,i.jsx)(t.a,{href:"https://adventofcode.com/2022/day/6",children:"Day 6: Tuning Trouble"})}),"\n",(0,i.jsx)(t.admonition,{title:"tl;dr",type:"info",children:(0,i.jsxs)(t.p,{children:["Finding start of the message in a very weird protocol. Start of the message is\ndenoted by ",(0,i.jsxs)(t.span,{className:"katex",children:[(0,i.jsx)(t.span,{className:"katex-mathml",children:(0,i.jsx)(t.math,{xmlns:"http://www.w3.org/1998/Math/MathML",children:(0,i.jsxs)(t.semantics,{children:[(0,i.jsx)(t.mrow,{children:(0,i.jsx)(t.mi,{children:"N"})}),(0,i.jsx)(t.annotation,{encoding:"application/x-tex",children:"N"})]})})}),(0,i.jsx)(t.span,{className:"katex-html","aria-hidden":"true",children:(0,i.jsxs)(t.span,{className:"base",children:[(0,i.jsx)(t.span,{className:"strut",style:{height:"0.6833em"}}),(0,i.jsx)(t.span,{className:"mord mathnormal",style:{marginRight:"0.10903em"},children:"N"})]})})]})," unique consecutive characters."]})}),"\n",(0,i.jsx)(t.h3,{id:"solution-5",children:"Solution"}),"\n",(0,i.jsx)(t.p,{children:"A 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",(0,i.jsxs)(t.p,{children:["One possible optimization could consist of keeping a bit-vector (i.e. ",(0,i.jsx)(t.code,{children:"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",(0,i.jsx)(t.p,{children:"Other 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",(0,i.jsx)(t.h2,{id:"day-7-no-space-left-on-device",children:(0,i.jsx)(t.a,{href:"https://adventofcode.com/2022/day/7",children:"Day 7: No Space Left On Device"})}),"\n",(0,i.jsx)(t.admonition,{title:"tl;dr",type:"info",children:(0,i.jsxs)(t.p,{children:["Let's simulate ",(0,i.jsx)(t.a,{href:"https://www.man7.org/linux/man-pages/man1/du.1.html",children:(0,i.jsx)(t.code,{children:"du"})})," to get some stats about our file system and then pinpoint\ndirectories that take a lot of space and should be deleted."]})}),"\n",(0,i.jsxs)(t.blockquote,{children:["\n",(0,i.jsxs)(t.p,{children:["I was waiting for this moment, and yet it got me!\n",(0,i.jsx)(t.em,{children:"imagine me swearing for hours"})]}),"\n"]}),"\n",(0,i.jsx)(t.h3,{id:"solution-6",children:"Solution"}),"\n",(0,i.jsxs)(t.p,{children:["We need to \u201c",(0,i.jsx)(t.em,{children:"build"}),"\u201d a file system from the input that is given in a following form:"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{children:"$ 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",(0,i.jsx)(t.p,{children:"There are few ways in which you can achieve this and also you can assume some\npreconditions, but why would we do that, right? :)"}),"\n",(0,i.jsxs)(t.p,{children:["You can \u201cslap\u201d this in either ",(0,i.jsx)(t.a,{href:"https://doc.rust-lang.org/std/collections/struct.HashMap.html",children:(0,i.jsx)(t.code,{children:"HashMap"})})," or ",(0,i.jsx)(t.a,{href:"https://doc.rust-lang.org/std/collections/struct.BTreeMap.html",children:(0,i.jsx)(t.code,{children:"BTreeMap"})})," and call it a day.\nAnd that would be boring\u2026"]}),"\n",(0,i.jsx)(t.admonition,{type:"tip",children:(0,i.jsxs)(t.p,{children:[(0,i.jsx)(t.code,{children:"BTreeMap"})," is quite fitting for this, don't you think?"]})}),"\n",(0,i.jsxs)(t.p,{children:["I always wanted to try allocation on heap in Rust, so I chose to implement a tree.\nI fought with the ",(0,i.jsx)(t.code,{children:"Box"})," for some time and was losing\u2026"]}),"\n",(0,i.jsxs)(t.p,{children:["Then I looked up some implementations of trees or linked lists and decided to try\n",(0,i.jsx)(t.code,{children:"Rc>"}),". And I got my ",(0,i.jsx)(t.em,{children:"ass whopped"})," by the compiler once again. /o\\"]}),"\n",(0,i.jsxs)(t.admonition,{type:"tip",children:[(0,i.jsxs)(t.p,{children:[(0,i.jsx)(t.code,{children:"Box"})," represents a dynamically allocated memory on heap. It is a single pointer,\nyou can imagine this as ",(0,i.jsx)(t.code,{children:"std::unique_ptr"})," in C++."]}),(0,i.jsxs)(t.p,{children:[(0,i.jsx)(t.code,{children:"Rc"})," represents a dynamically allocated memory on heap. On top of that it is\n",(0,i.jsx)(t.em,{children:"reference counted"})," (that's what the ",(0,i.jsx)(t.code,{children:"Rc"})," stands for). You can imagine this as\n",(0,i.jsx)(t.code,{children:"std::shared_ptr"})," in C++."]}),(0,i.jsxs)(t.p,{children:["Now the fun stuff. Neither of them lets you ",(0,i.jsx)(t.strong,{children:"mutate"})," the contents of the memory."]}),(0,i.jsxs)(t.p,{children:[(0,i.jsx)(t.code,{children:"Cell"})," 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 ",(0,i.jsx)(t.strong,{children:"mutable"})," reference to the memory."]}),(0,i.jsxs)(t.p,{children:[(0,i.jsx)(t.code,{children:"RefCell"})," is similar to the ",(0,i.jsx)(t.code,{children:"Cell"}),", but the borrowing rules (how many mutable\nreferences are present) are checked dynamically."]}),(0,i.jsxs)(t.p,{children:["So in the end, if you want something like ",(0,i.jsx)(t.code,{children:"std::shared_ptr"})," in Rust, you want\nto have ",(0,i.jsx)(t.code,{children:"Rc>"}),"."]})]}),"\n",(0,i.jsxs)(t.p,{children:["So, 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 ","\ud83d\ude29"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-rust",children:"type FileHandle = Rc>;\n\n#[derive(Debug)]\nenum AocFile {\n File(usize),\n Directory(BTreeMap),\n}\n"})}),"\n",(0,i.jsxs)(t.p,{children:["Let's go over it! ",(0,i.jsx)(t.code,{children:"FileHandle"})," represents dynamically allocated ",(0,i.jsx)(t.code,{children:"AocFile"}),", not\nmuch to discuss. What does the ",(0,i.jsx)(t.code,{children:"#[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",(0,i.jsxs)(t.p,{children:["Now to the fun part! ",(0,i.jsx)(t.code,{children:"AocFile"})," value can be represented in two ways:"]}),"\n",(0,i.jsxs)(t.ul,{children:["\n",(0,i.jsxs)(t.li,{children:[(0,i.jsx)(t.code,{children:"File(usize)"}),", e.g. ",(0,i.jsx)(t.code,{children:"AocFile::File(123)"})," and we can pattern match it, if we\nneed to"]}),"\n",(0,i.jsxs)(t.li,{children:[(0,i.jsx)(t.code,{children:"Directory(BTreeMap)"})," will represent the directory and will\ncontain map matching the name of the files (or directories) within to their\nrespective file handles"]}),"\n"]}),"\n",(0,i.jsx)(t.p,{children:"I 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",(0,i.jsx)(t.p,{children:"We 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",(0,i.jsxs)(t.p,{children:["I have chosen to implement ",(0,i.jsx)(t.a,{href:"https://en.wikipedia.org/wiki/Catamorphism#Tree_fold",children:(0,i.jsx)(t.em,{children:"tree catamorphism"})})," ","\ud83d\ude29",". 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 ",(0,i.jsx)(t.em,{children:"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",(0,i.jsx)(t.p,{children:"Another 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",(0,i.jsx)(t.p,{children:"One 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",(0,i.jsx)(t.h2,{id:"post-mortem",children:"Post Mortem"}),"\n",(0,i.jsx)(t.p,{children:"Things that have been brought up in the discussion later on."}),"\n",(0,i.jsxs)(t.h3,{id:"rct-vs-rcrefcellt",children:[(0,i.jsx)(t.code,{children:"Rc"})," vs ",(0,i.jsx)(t.code,{children:"Rc>"})]}),"\n",(0,i.jsx)(t.p,{children:"It has been brought up that I have a contradicting statement regarding the\ndynamically allocated memory. Specifically:"}),"\n",(0,i.jsxs)(t.ul,{children:["\n",(0,i.jsxs)(t.li,{children:["You can imagine ",(0,i.jsx)(t.code,{children:"Rc"})," as an ",(0,i.jsx)(t.code,{children:"std::shared_ptr"})," (in C++)"]}),"\n",(0,i.jsxs)(t.li,{children:["When you want an equivalent of ",(0,i.jsx)(t.code,{children:"std::shared_ptr"}),", you want to use\n",(0,i.jsx)(t.code,{children:"Rc>"})]}),"\n"]}),"\n",(0,i.jsxs)(t.p,{children:["Now, in Rust it is a bit more complicated, because the type that represents the\n\u201cshared pointer\u201d is ",(0,i.jsx)(t.code,{children:"Rc"}),". What ",(0,i.jsx)(t.code,{children:"RefCell"})," does is making sure that there is\nonly one \u201cowner\u201d of a mutable reference at a time (and dynamically, as opposed\nto the ",(0,i.jsx)(t.code,{children:"Cell"}),")."]}),"\n",(0,i.jsxs)(t.p,{children:["Therefore to be precise and correct about the equivalents of ",(0,i.jsx)(t.code,{children:"std::shared_ptr"}),"\nin Rust, we can say that"]}),"\n",(0,i.jsxs)(t.ul,{children:["\n",(0,i.jsxs)(t.li,{children:[(0,i.jsx)(t.code,{children:"Rc"})," is an equivalent of a ",(0,i.jsx)(t.code,{children:"const std::shared_ptr"}),","]}),"\n",(0,i.jsxs)(t.li,{children:["and ",(0,i.jsx)(t.code,{children:"Rc>"})," is an equivalent of a ",(0,i.jsx)(t.code,{children:"std::shared_ptr"}),"."]}),"\n"]}),"\n",(0,i.jsxs)(t.p,{children:["You can easily see that they only differ in the mutability. (And even that is not\nas simple as it seems, because there is also ",(0,i.jsx)(t.code,{children:"Cell"}),")"]})]})}function h(e={}){const{wrapper:t}={...(0,o.a)(),...e.components};return t?(0,i.jsx)(t,{...e,children:(0,i.jsx)(d,{...e})}):d(e)}},11151:(e,t,n)=>{n.d(t,{Z:()=>l,a:()=>a});var i=n(67294);const o={},s=i.createContext(o);function a(e){const t=i.useContext(s);return i.useMemo((function(){return"function"==typeof e?e(t):{...t,...e}}),[t,e])}function l(e){let t;return t=e.disableParentContext?"function"==typeof e.components?e.components(o):e.components||o:a(e.components),i.createElement(s.Provider,{value:t},e.children)}}}]); \ No newline at end of file +"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[146],{42492:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>r,contentTitle:()=>a,default:()=>h,frontMatter:()=>s,metadata:()=>l,toc:()=>c});var i=n(85893),o=n(11151);const s={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:!1},a=void 0,l={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:!0,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:!1},unlisted:!1,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"}},r={authorsImageUrls:[void 0]},c=[{value:"Day 1: Calorie Counting",id:"day-1-calorie-counting",level:2},{value:"Solution",id:"solution",level:3},{value:"Day 2: Rock Paper Scissors",id:"day-2-rock-paper-scissors",level:2},{value:"Solution",id:"solution-1",level:3},{value:"Day 3: Rucksack Reorganization",id:"day-3-rucksack-reorganization",level:2},{value:"Solution",id:"solution-2",level:3},{value:"Day 4: Camp Cleanup",id:"day-4-camp-cleanup",level:2},{value:"Solution",id:"solution-3",level:3},{value:"Day 5: Supply Stacks",id:"day-5-supply-stacks",level:2},{value:"Solution",id:"solution-4",level:3},{value:"Day 6: Tuning Trouble",id:"day-6-tuning-trouble",level:2},{value:"Solution",id:"solution-5",level:3},{value:"Day 7: No Space Left On Device",id:"day-7-no-space-left-on-device",level:2},{value:"Solution",id:"solution-6",level:3},{value:"Post Mortem",id:"post-mortem",level:2},{value:"Rc<T> vs Rc<RefCell<T>>",id:"rct-vs-rcrefcellt",level:3}];function d(e){const t={a:"a",admonition:"admonition",annotation:"annotation",blockquote:"blockquote",code:"code",del:"del",em:"em",h2:"h2",h3:"h3",li:"li",math:"math",mi:"mi",mrow:"mrow",p:"p",pre:"pre",semantics:"semantics",span:"span",strong:"strong",ul:"ul",...(0,o.a)(),...e.components};return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)(t.p,{children:["Let's go through the first week of ",(0,i.jsx)(t.a,{href:"https://adventofcode.com",children:(0,i.jsx)(t.em,{children:"Advent of Code"})})," in Rust."]}),"\n",(0,i.jsx)(t.admonition,{type:"note",children:(0,i.jsxs)(t.p,{children:["If you wish to have a look at the solutions, you can follow them on my ",(0,i.jsx)(t.a,{href:"https://gitlab.com/mfocko/advent-of-code-2022",children:"GitLab"}),".\nMore specifically in the ",(0,i.jsx)(t.a,{href:"https://gitlab.com/mfocko/advent-of-code-2022/-/tree/main/src/bin",children:(0,i.jsx)(t.code,{children:"/src/bin/"})}),"."]})}),"\n",(0,i.jsxs)(t.p,{children:["I will try to summarize my experience with using Rust for the AoC. Trying it out\nages ago, I believe it will be ",(0,i.jsx)(t.em,{children:"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 ","\ud83d\udc4d"," moments."]}),"\n",(0,i.jsx)(t.h2,{id:"day-1-calorie-counting",children:(0,i.jsx)(t.a,{href:"https://adventofcode.com/2022/day/1",children:"Day 1: Calorie Counting"})}),"\n",(0,i.jsx)(t.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(t.p,{children:"As 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",(0,i.jsxs)(t.blockquote,{children:["\n",(0,i.jsx)(t.p,{children:"Wakey wakey!"}),"\n"]}),"\n",(0,i.jsx)(t.p,{children:"Programming 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",(0,i.jsxs)(t.p,{children:["At first I've decided to put asserts into my ",(0,i.jsx)(t.code,{children:"main"}),", something like"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-rust",children:'assert_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",(0,i.jsx)(t.p,{children:"However, 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",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-rust",children:'#[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",(0,i.jsxs)(t.p,{children:["And later on I have noticed, it's hard to tell the difference between the days,\nso I further renamed the ",(0,i.jsx)(t.code,{children:"mod"})," from generic ",(0,i.jsx)(t.code,{children:"tests"})," to reflect the days."]}),"\n",(0,i.jsxs)(t.p,{children:["Also after finishing the first day puzzle, I have installed an ",(0,i.jsx)(t.a,{href:"https://github.com/mozilla/sccache",children:(0,i.jsx)(t.code,{children:"sccache"})})," to\ncache the builds, so that the build time is lower, cause it was kinda unbearable."]}),"\n",(0,i.jsx)(t.h3,{id:"solution",children:"Solution"}),"\n",(0,i.jsx)(t.p,{children:"Well, 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",(0,i.jsxs)(t.ul,{children:["\n",(0,i.jsx)(t.li,{children:"keep all the calories, sort them, take what we need"}),"\n",(0,i.jsx)(t.li,{children:"keep all the calories and use max heap"}),"\n",(0,i.jsx)(t.li,{children:"use min heap and maintain at most N calories that we need"}),"\n"]}),"\n",(0,i.jsx)(t.h2,{id:"day-2-rock-paper-scissors",children:(0,i.jsx)(t.a,{href:"https://adventofcode.com/2022/day/2",children:"Day 2: Rock Paper Scissors"})}),"\n",(0,i.jsx)(t.admonition,{title:"tl;dr",type:"info",children:(0,i.jsxs)(t.p,{children:["You want to know what score did you achieve while playing ",(0,i.jsx)(t.em,{children:"Rock Paper Scissors"}),".\nAnd then you want to be strategic about it."]})}),"\n",(0,i.jsx)(t.p,{children:"Apart from the technical details of the puzzle, it went relatively smooth."}),"\n",(0,i.jsx)(t.h3,{id:"solution-1",children:"Solution"}),"\n",(0,i.jsx)(t.p,{children:"I took relatively na\xefve approach and then tried to simplify it."}),"\n",(0,i.jsx)(t.h2,{id:"day-3-rucksack-reorganization",children:(0,i.jsx)(t.a,{href:"https://adventofcode.com/2022/day/3",children:"Day 3: Rucksack Reorganization"})}),"\n",(0,i.jsx)(t.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(t.p,{children:"Let'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",(0,i.jsx)(t.p,{children:"This 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",(0,i.jsx)(t.admonition,{title:"Fun fact",type:"tip",children:(0,i.jsx)(t.p,{children:"Fighting the compiler took me 30 minutes."})}),"\n",(0,i.jsx)(t.p,{children:"We 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",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-rust",children:"let top: HashSet = [1, 2, 3].iter().collect();\nlet bottom: HashSet = [3, 4, 5].iter().collect();\n"})}),"\n",(0,i.jsxs)(t.p,{children:["Now, the first issue that we encounter is caused by the fact that we are using\na slice (the ",(0,i.jsx)(t.code,{children:"[\u2026]"}),"), iterator of that returns ",(0,i.jsx)(t.strong,{children:"references"})," to the numbers.\nAnd we get immediately yelled at by the compiler, because the numbers are discarded\nafter running the ",(0,i.jsx)(t.code,{children:".collect"}),". To fix this, we can use ",(0,i.jsx)(t.code,{children:".into_iter"}),":"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-rust",children:"let top: HashSet = [1, 2, 3].into_iter().collect();\nlet bottom: HashSet = [3, 4, 5].into_iter().collect();\n"})}),"\n",(0,i.jsx)(t.p,{children:"This way the numbers will get copied instead of referenced. OK, let's find the\nintersection of those 2 collections:"}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-rust",children:'println!("Common elements: {:?}", top.intersection(&bottom));\n'})}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{children:"Common elements: [3]\n"})}),"\n",(0,i.jsx)(t.admonition,{type:"caution",children:(0,i.jsxs)(t.p,{children:["Notice that we need to do ",(0,i.jsx)(t.code,{children:"&bottom"}),". It explicitly specifies that ",(0,i.jsx)(t.code,{children:".intersection"}),"\n",(0,i.jsx)(t.strong,{children:"borrows"})," the ",(0,i.jsx)(t.code,{children:"bottom"}),", i.e. takes an immutable reference to it."]})}),"\n",(0,i.jsx)(t.p,{children:"That's what we want, right? Looks like it! \\o/"}),"\n",(0,i.jsx)(t.p,{children:"Next 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",(0,i.jsxs)(t.p,{children:["Let's have a look at the type of the ",(0,i.jsx)(t.code,{children:".intersection"})]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-rust",children:"pub fn intersection<'a>(\n\xa0\xa0\xa0\xa0&'a self,\n\xa0\xa0\xa0\xa0other: &'a HashSet\n) -> Intersection<'a, T, S>\n"})}),"\n",(0,i.jsx)(t.p,{children:"OK\u2026 Huh\u2026 But we have an example there!"}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-rust",children:"let intersection: HashSet<_> = a.intersection(&b).collect();\n"})}),"\n",(0,i.jsx)(t.p,{children:"Cool, that's all we need."}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-rust",children:'let top: HashSet = [1, 2, 3, 4].into_iter().collect();\nlet bottom: HashSet = [3, 4, 5, 6].into_iter().collect();\nlet top_2: HashSet = [2, 3, 4, 5, 6].into_iter().collect();\nlet bottom_2: HashSet = [4, 5, 6].into_iter().collect();\n\nlet intersection: HashSet<_> = top.intersection(&bottom).collect();\nprintln!("Intersection: {:?}", intersection);\n'})}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{children:"Intersection: {3, 4}\n"})}),"\n",(0,i.jsxs)(t.p,{children:["Cool, so let's do the intersection with the ",(0,i.jsx)(t.code,{children:"top_2"}),":"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-rust",children:'let top: HashSet = [1, 2, 3, 4].into_iter().collect();\nlet bottom: HashSet = [3, 4, 5, 6].into_iter().collect();\nlet top_2: HashSet = [2, 3, 4, 5, 6].into_iter().collect();\nlet bottom_2: HashSet = [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",(0,i.jsx)(t.p,{children:"And we get yelled at by the compiler:"}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{children:"error[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`\n"})}),"\n",(0,i.jsx)(t.p,{children:"/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",(0,i.jsx)(t.admonition,{type:"tip",children:(0,i.jsxs)(t.p,{children:["It 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 ",(0,i.jsx)(t.del,{children:"drilling your ass"})," having your back and\nmaking sure you're not doing something naughty that may cause an ",(0,i.jsx)(t.strong,{children:"undefined"}),"\n",(0,i.jsx)(t.strong,{children:"behavior"}),"."]})}),"\n",(0,i.jsxs)(t.p,{children:["To resolve this we need to get an iterator that ",(0,i.jsx)(t.strong,{children:"clones"})," the elements:"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-rust",children:'let top: HashSet = [1, 2, 3, 4].into_iter().collect();\nlet bottom: HashSet = [3, 4, 5, 6].into_iter().collect();\nlet top_2: HashSet = [2, 3, 4, 5, 6].into_iter().collect();\nlet bottom_2: HashSet = [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",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{children:"Intersection: {4}\n"})}),"\n",(0,i.jsx)(t.h3,{id:"solution-2",children:"Solution"}),"\n",(0,i.jsxs)(t.p,{children:["The approach is pretty simple, if you omit the ",(0,i.jsx)(t.em,{children:"1on1 with the compiler"}),". You just\nhave some fun with the set operations :)"]}),"\n",(0,i.jsx)(t.h2,{id:"day-4-camp-cleanup",children:(0,i.jsx)(t.a,{href:"https://adventofcode.com/2022/day/4",children:"Day 4: Camp Cleanup"})}),"\n",(0,i.jsx)(t.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(t.p,{children:"Elves are cleaning up the camp and they got overlapping sections to clean up.\nFind how many overlap and can take the day off."})}),"\n",(0,i.jsxs)(t.p,{children:[(0,i.jsx)(t.a,{href:"https://doc.rust-lang.org/std/ops/struct.RangeInclusive.html",children:(0,i.jsx)(t.code,{children:"RangeInclusive"})})," is your friend not an enemy :)"]}),"\n",(0,i.jsx)(t.h3,{id:"solution-3",children:"Solution"}),"\n",(0,i.jsxs)(t.p,{children:["Relatively easy, you just need to parse the input and know what you want. Rust's\n",(0,i.jsx)(t.code,{children:"RangeInclusive"})," type helped a lot, cause it took care of all abstractions."]}),"\n",(0,i.jsx)(t.h2,{id:"day-5-supply-stacks",children:(0,i.jsx)(t.a,{href:"https://adventofcode.com/2022/day/5",children:"Day 5: Supply Stacks"})}),"\n",(0,i.jsx)(t.admonition,{title:"tl;dr",type:"info",children:(0,i.jsx)(t.p,{children:"Let's play with stacks of crates."})}),"\n",(0,i.jsx)(t.p,{children:"Very easy problem with very annoying input. You can judge yourself:"}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{children:" [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",(0,i.jsx)(t.p,{children:"Good luck transforming that into something reasonable :)"}),"\n",(0,i.jsx)(t.admonition,{title:"Fun fact",type:"tip",children:(0,i.jsx)(t.p,{children:"Took me 40 minutes to parse this reasonably, including fighting the compiler."})}),"\n",(0,i.jsx)(t.h3,{id:"solution-4",children:"Solution"}),"\n",(0,i.jsxs)(t.p,{children:["For the initial solution I went with a manual solution (as in ",(0,i.jsx)(t.em,{children:"I have done all"}),"\n",(0,i.jsx)(t.em,{children:"the work"}),". Later on I have decided to explore the ",(0,i.jsx)(t.code,{children:"std"})," and interface of the\n",(0,i.jsx)(t.code,{children:"std::vec::Vec"})," and found ",(0,i.jsx)(t.a,{href:"https://doc.rust-lang.org/std/vec/struct.Vec.html#method.split_off",children:(0,i.jsx)(t.code,{children:"split_off"})})," which takes an index and splits (duh)\nthe vector:"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-rust",children:"let mut vec = vec![1, 2, 3];\nlet vec2 = vec.split_off(1);\nassert_eq!(vec, [1]);\nassert_eq!(vec2, [2, 3]);\n"})}),"\n",(0,i.jsxs)(t.p,{children:["This helped me simplify my solution a lot and also get rid of some ",(0,i.jsx)(t.em,{children:"edge cases"}),"."]}),"\n",(0,i.jsx)(t.h2,{id:"day-6-tuning-trouble",children:(0,i.jsx)(t.a,{href:"https://adventofcode.com/2022/day/6",children:"Day 6: Tuning Trouble"})}),"\n",(0,i.jsx)(t.admonition,{title:"tl;dr",type:"info",children:(0,i.jsxs)(t.p,{children:["Finding start of the message in a very weird protocol. Start of the message is\ndenoted by ",(0,i.jsxs)(t.span,{className:"katex",children:[(0,i.jsx)(t.span,{className:"katex-mathml",children:(0,i.jsx)(t.math,{xmlns:"http://www.w3.org/1998/Math/MathML",children:(0,i.jsxs)(t.semantics,{children:[(0,i.jsx)(t.mrow,{children:(0,i.jsx)(t.mi,{children:"N"})}),(0,i.jsx)(t.annotation,{encoding:"application/x-tex",children:"N"})]})})}),(0,i.jsx)(t.span,{className:"katex-html","aria-hidden":"true",children:(0,i.jsxs)(t.span,{className:"base",children:[(0,i.jsx)(t.span,{className:"strut",style:{height:"0.6833em"}}),(0,i.jsx)(t.span,{className:"mord mathnormal",style:{marginRight:"0.10903em"},children:"N"})]})})]})," unique consecutive characters."]})}),"\n",(0,i.jsx)(t.h3,{id:"solution-5",children:"Solution"}),"\n",(0,i.jsx)(t.p,{children:"A 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",(0,i.jsxs)(t.p,{children:["One possible optimization could consist of keeping a bit-vector (i.e. ",(0,i.jsx)(t.code,{children:"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",(0,i.jsx)(t.p,{children:"Other 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",(0,i.jsx)(t.h2,{id:"day-7-no-space-left-on-device",children:(0,i.jsx)(t.a,{href:"https://adventofcode.com/2022/day/7",children:"Day 7: No Space Left On Device"})}),"\n",(0,i.jsx)(t.admonition,{title:"tl;dr",type:"info",children:(0,i.jsxs)(t.p,{children:["Let's simulate ",(0,i.jsx)(t.a,{href:"https://www.man7.org/linux/man-pages/man1/du.1.html",children:(0,i.jsx)(t.code,{children:"du"})})," to get some stats about our file system and then pinpoint\ndirectories that take a lot of space and should be deleted."]})}),"\n",(0,i.jsxs)(t.blockquote,{children:["\n",(0,i.jsxs)(t.p,{children:["I was waiting for this moment, and yet it got me!\n",(0,i.jsx)(t.em,{children:"imagine me swearing for hours"})]}),"\n"]}),"\n",(0,i.jsx)(t.h3,{id:"solution-6",children:"Solution"}),"\n",(0,i.jsxs)(t.p,{children:["We need to \u201c",(0,i.jsx)(t.em,{children:"build"}),"\u201d a file system from the input that is given in a following form:"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{children:"$ 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",(0,i.jsx)(t.p,{children:"There are few ways in which you can achieve this and also you can assume some\npreconditions, but why would we do that, right? :)"}),"\n",(0,i.jsxs)(t.p,{children:["You can \u201cslap\u201d this in either ",(0,i.jsx)(t.a,{href:"https://doc.rust-lang.org/std/collections/struct.HashMap.html",children:(0,i.jsx)(t.code,{children:"HashMap"})})," or ",(0,i.jsx)(t.a,{href:"https://doc.rust-lang.org/std/collections/struct.BTreeMap.html",children:(0,i.jsx)(t.code,{children:"BTreeMap"})})," and call it a day.\nAnd that would be boring\u2026"]}),"\n",(0,i.jsx)(t.admonition,{type:"tip",children:(0,i.jsxs)(t.p,{children:[(0,i.jsx)(t.code,{children:"BTreeMap"})," is quite fitting for this, don't you think?"]})}),"\n",(0,i.jsxs)(t.p,{children:["I always wanted to try allocation on heap in Rust, so I chose to implement a tree.\nI fought with the ",(0,i.jsx)(t.code,{children:"Box"})," for some time and was losing\u2026"]}),"\n",(0,i.jsxs)(t.p,{children:["Then I looked up some implementations of trees or linked lists and decided to try\n",(0,i.jsx)(t.code,{children:"Rc>"}),". And I got my ",(0,i.jsx)(t.em,{children:"ass whopped"})," by the compiler once again. /o\\"]}),"\n",(0,i.jsxs)(t.admonition,{type:"tip",children:[(0,i.jsxs)(t.p,{children:[(0,i.jsx)(t.code,{children:"Box"})," represents a dynamically allocated memory on heap. It is a single pointer,\nyou can imagine this as ",(0,i.jsx)(t.code,{children:"std::unique_ptr"})," in C++."]}),(0,i.jsxs)(t.p,{children:[(0,i.jsx)(t.code,{children:"Rc"})," represents a dynamically allocated memory on heap. On top of that it is\n",(0,i.jsx)(t.em,{children:"reference counted"})," (that's what the ",(0,i.jsx)(t.code,{children:"Rc"})," stands for). You can imagine this as\n",(0,i.jsx)(t.code,{children:"std::shared_ptr"})," in C++."]}),(0,i.jsxs)(t.p,{children:["Now the fun stuff. Neither of them lets you ",(0,i.jsx)(t.strong,{children:"mutate"})," the contents of the memory."]}),(0,i.jsxs)(t.p,{children:[(0,i.jsx)(t.code,{children:"Cell"})," 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 ",(0,i.jsx)(t.strong,{children:"mutable"})," reference to the memory."]}),(0,i.jsxs)(t.p,{children:[(0,i.jsx)(t.code,{children:"RefCell"})," is similar to the ",(0,i.jsx)(t.code,{children:"Cell"}),", but the borrowing rules (how many mutable\nreferences are present) are checked dynamically."]}),(0,i.jsxs)(t.p,{children:["So in the end, if you want something like ",(0,i.jsx)(t.code,{children:"std::shared_ptr"})," in Rust, you want\nto have ",(0,i.jsx)(t.code,{children:"Rc>"}),"."]})]}),"\n",(0,i.jsxs)(t.p,{children:["So, 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 ","\ud83d\ude29"]}),"\n",(0,i.jsx)(t.pre,{children:(0,i.jsx)(t.code,{className:"language-rust",children:"type FileHandle = Rc>;\n\n#[derive(Debug)]\nenum AocFile {\n File(usize),\n Directory(BTreeMap),\n}\n"})}),"\n",(0,i.jsxs)(t.p,{children:["Let's go over it! ",(0,i.jsx)(t.code,{children:"FileHandle"})," represents dynamically allocated ",(0,i.jsx)(t.code,{children:"AocFile"}),", not\nmuch to discuss. What does the ",(0,i.jsx)(t.code,{children:"#[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",(0,i.jsxs)(t.p,{children:["Now to the fun part! ",(0,i.jsx)(t.code,{children:"AocFile"})," value can be represented in two ways:"]}),"\n",(0,i.jsxs)(t.ul,{children:["\n",(0,i.jsxs)(t.li,{children:[(0,i.jsx)(t.code,{children:"File(usize)"}),", e.g. ",(0,i.jsx)(t.code,{children:"AocFile::File(123)"})," and we can pattern match it, if we\nneed to"]}),"\n",(0,i.jsxs)(t.li,{children:[(0,i.jsx)(t.code,{children:"Directory(BTreeMap)"})," will represent the directory and will\ncontain map matching the name of the files (or directories) within to their\nrespective file handles"]}),"\n"]}),"\n",(0,i.jsx)(t.p,{children:"I 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",(0,i.jsx)(t.p,{children:"We 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",(0,i.jsxs)(t.p,{children:["I have chosen to implement ",(0,i.jsx)(t.a,{href:"https://en.wikipedia.org/wiki/Catamorphism#Tree_fold",children:(0,i.jsx)(t.em,{children:"tree catamorphism"})})," ","\ud83d\ude29",". 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 ",(0,i.jsx)(t.em,{children:"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",(0,i.jsx)(t.p,{children:"Another 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",(0,i.jsx)(t.p,{children:"One 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",(0,i.jsx)(t.h2,{id:"post-mortem",children:"Post Mortem"}),"\n",(0,i.jsx)(t.p,{children:"Things that have been brought up in the discussion later on."}),"\n",(0,i.jsxs)(t.h3,{id:"rct-vs-rcrefcellt",children:[(0,i.jsx)(t.code,{children:"Rc"})," vs ",(0,i.jsx)(t.code,{children:"Rc>"})]}),"\n",(0,i.jsx)(t.p,{children:"It has been brought up that I have a contradicting statement regarding the\ndynamically allocated memory. Specifically:"}),"\n",(0,i.jsxs)(t.ul,{children:["\n",(0,i.jsxs)(t.li,{children:["You can imagine ",(0,i.jsx)(t.code,{children:"Rc"})," as an ",(0,i.jsx)(t.code,{children:"std::shared_ptr"})," (in C++)"]}),"\n",(0,i.jsxs)(t.li,{children:["When you want an equivalent of ",(0,i.jsx)(t.code,{children:"std::shared_ptr"}),", you want to use\n",(0,i.jsx)(t.code,{children:"Rc>"})]}),"\n"]}),"\n",(0,i.jsxs)(t.p,{children:["Now, in Rust it is a bit more complicated, because the type that represents the\n\u201cshared pointer\u201d is ",(0,i.jsx)(t.code,{children:"Rc"}),". What ",(0,i.jsx)(t.code,{children:"RefCell"})," does is making sure that there is\nonly one \u201cowner\u201d of a mutable reference at a time (and dynamically, as opposed\nto the ",(0,i.jsx)(t.code,{children:"Cell"}),")."]}),"\n",(0,i.jsxs)(t.p,{children:["Therefore to be precise and correct about the equivalents of ",(0,i.jsx)(t.code,{children:"std::shared_ptr"}),"\nin Rust, we can say that"]}),"\n",(0,i.jsxs)(t.ul,{children:["\n",(0,i.jsxs)(t.li,{children:[(0,i.jsx)(t.code,{children:"Rc"})," is an equivalent of a ",(0,i.jsx)(t.code,{children:"const std::shared_ptr"}),","]}),"\n",(0,i.jsxs)(t.li,{children:["and ",(0,i.jsx)(t.code,{children:"Rc>"})," is an equivalent of a ",(0,i.jsx)(t.code,{children:"std::shared_ptr"}),"."]}),"\n"]}),"\n",(0,i.jsxs)(t.p,{children:["You can easily see that they only differ in the mutability. (And even that is not\nas simple as it seems, because there is also ",(0,i.jsx)(t.code,{children:"Cell"}),")"]})]})}function h(e={}){const{wrapper:t}={...(0,o.a)(),...e.components};return t?(0,i.jsx)(t,{...e,children:(0,i.jsx)(d,{...e})}):d(e)}},11151:(e,t,n)=>{n.d(t,{Z:()=>l,a:()=>a});var i=n(67294);const o={},s=i.createContext(o);function a(e){const t=i.useContext(s);return i.useMemo((function(){return"function"==typeof e?e(t):{...t,...e}}),[t,e])}function l(e){let t;return t=e.disableParentContext?"function"==typeof e.components?e.components(o):e.components||o:a(e.components),i.createElement(s.Provider,{value:t},e.children)}}}]); \ No newline at end of file diff --git a/assets/js/f48be158.3578ba3c.js b/assets/js/f48be158.3578ba3c.js new file mode 100644 index 0000000..2bc6ca1 --- /dev/null +++ b/assets/js/f48be158.3578ba3c.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[4064],{12326:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>l,contentTitle:()=>a,default:()=>h,frontMatter:()=>r,metadata:()=>s,toc:()=>d});var o=t(85893),i=t(11151);const r={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:!1},a=void 0,s={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.57,hasTruncateMarker:!0,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:!1},unlisted:!1,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"}},l={authorsImageUrls:[void 0]},d=[{value:"Day 15: Beacon Exclusion Zone",id:"day-15-beacon-exclusion-zone",level:2},{value:"Solution",id:"solution",level:3},{value:"Day 16: Proboscidea Volcanium",id:"day-16-proboscidea-volcanium",level:2},{value:"Solution",id:"solution-1",level:3},{value:"Indexing in graph",id:"indexing-in-graph",level:4},{value:"Cartesian product",id:"cartesian-product",level:4},{value:"\u201cImplementing\u201d an iterator",id:"implementing-an-iterator",level:4},{value:"Day 17: Pyroclastic Flow",id:"day-17-pyroclastic-flow",level:2},{value:"Solution",id:"solution-2",level:3},{value:"Collision detection",id:"collision-detection",level:4},{value:"Infinite iterator",id:"infinite-iterator",level:4},{value:"Day 18: Boiling Boulders",id:"day-18-boiling-boulders",level:2},{value:"Solution",id:"solution-3",level:3},{value:"Day 19: Not Enough Minerals",id:"day-19-not-enough-minerals",level:2},{value:"Solution",id:"solution-4",level:3},{value:"Day 20: Grove Positioning System",id:"day-20-grove-positioning-system",level:2},{value:"Solution",id:"solution-5",level:3},{value:".borrow_mut()",id:"borrow_mut",level:4},{value:".borrow_mut() on Rc<RefCell<T>>",id:"borrow_mut-on-rcrefcellt",level:5},{value:"BorrowMut trait",id:"borrowmut-trait",level:5},{value:"Conflict",id:"conflict",level:5},{value:"Day 21: Monkey Math",id:"day-21-monkey-math",level:2},{value:"Solution",id:"solution-6",level:3},{value:"Default trait",id:"default-trait",level:4},{value:"Abusing negation",id:"abusing-negation",level:4}];function c(e){const n={a:"a",admonition:"admonition",blockquote:"blockquote",code:"code",em:"em",h2:"h2",h3:"h3",h4:"h4",h5:"h5",li:"li",ol:"ol",p:"p",pre:"pre",section:"section",strong:"strong",sup:"sup",ul:"ul",...(0,i.a)(),...e.components};return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)(n.p,{children:["Let's go through the third week of ",(0,o.jsx)(n.a,{href:"https://adventofcode.com",children:(0,o.jsx)(n.em,{children:"Advent of Code"})})," in Rust."]}),"\n",(0,o.jsx)(n.h2,{id:"day-15-beacon-exclusion-zone",children:(0,o.jsx)(n.a,{href:"https://adventofcode.com/2022/day/15",children:"Day 15: Beacon Exclusion Zone"})}),"\n",(0,o.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,o.jsx)(n.p,{children:"Triangulating a distress beacon based on the information from the sensors."})}),"\n",(0,o.jsx)(n.h3,{id:"solution",children:"Solution"}),"\n",(0,o.jsx)(n.p,{children:"Relatively easy thing to implement, no major Rust issues hit."}),"\n",(0,o.jsx)(n.h2,{id:"day-16-proboscidea-volcanium",children:(0,o.jsx)(n.a,{href:"https://adventofcode.com/2022/day/16",children:"Day 16: Proboscidea Volcanium"})}),"\n",(0,o.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,o.jsx)(n.p,{children:"Finding a max flow in a graph given some time constraints."})}),"\n",(0,o.jsx)(n.h3,{id:"solution-1",children:"Solution"}),"\n",(0,o.jsx)(n.p,{children:"I have used some interesting things to implement this and make it easier for me."}),"\n",(0,o.jsx)(n.h4,{id:"indexing-in-graph",children:"Indexing in graph"}),"\n",(0,o.jsx)(n.p,{children:"I 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",(0,o.jsx)(n.p,{children:"Here you can see a rather short snippet from the solution that allows you to\n\u201cindex\u201d the graph:"}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-rust",children:"impl 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",(0,o.jsx)(n.h4,{id:"cartesian-product",children:"Cartesian product"}),"\n",(0,o.jsxs)(n.p,{children:["During the implementation I had to utilize Floyd-Warshall algorithm for finding\nthe shortest path between pairs of vertices and utilized the ",(0,o.jsx)(n.code,{children:"iproduct!"})," macro\nfrom the ",(0,o.jsx)(n.a,{href:"https://crates.io/crates/itertools",children:(0,o.jsx)(n.code,{children:"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",(0,o.jsx)(n.h4,{id:"implementing-an-iterator",children:"\u201cImplementing\u201d an iterator"}),"\n",(0,o.jsx)(n.p,{children:"For 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",(0,o.jsxs)(n.p,{children:["Being affected by ",(0,o.jsx)(n.em,{children:"functional programming brain damage"}),"\u2122\ufe0f",", I have chosen to\ndo this part by function that returns an iterator over the possible ways:"]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-rust",children:"fn pairings(\n valves: &BTreeSet,\n) -> impl Iterator, BTreeSet)> + '_ {\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",(0,o.jsx)(n.h2,{id:"day-17-pyroclastic-flow",children:(0,o.jsx)(n.a,{href:"https://adventofcode.com/2022/day/17",children:"Day 17: Pyroclastic Flow"})}),"\n",(0,o.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,o.jsx)(n.p,{children:"Simulating an autonomous Tetris where pieces get affected by a series of jets of\nhot gas."})}),"\n",(0,o.jsx)(n.h3,{id:"solution-2",children:"Solution"}),"\n",(0,o.jsxs)(n.p,{children:["Similarly to the previous day I have created some iterators ","\ud83d\ude04"]}),"\n",(0,o.jsx)(n.h4,{id:"collision-detection",children:"Collision detection"}),"\n",(0,o.jsx)(n.p,{children:"Once 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",(0,o.jsx)(n.p,{children:"To get the desired behaviour, you can just compose few smaller functions:"}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-rust",children:"fn occupied(shape: &[Vec]) -> impl Iterator + '_ {\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",(0,o.jsx)(n.p,{children:"In 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",(0,o.jsxs)(n.ul,{children:["\n",(0,o.jsxs)(n.li,{children:[(0,o.jsx)(n.code,{children:".enumerate()"})," allows us to get both the indices (coordinates) and the line\nor, later on, the character itself,"]}),"\n",(0,o.jsxs)(n.li,{children:[(0,o.jsx)(n.code,{children:".flat_map()"})," flattens the iterator, i.e. when we return another iterator,\nthey just get chained instead of iterating over iterators (which sounds pretty\ndisturbing, doesn't it?),"]}),"\n",(0,o.jsxs)(n.li,{children:["and finally ",(0,o.jsx)(n.code,{children:".filter_map()"})," which is pretty similar to the \u201cbasic\u201d ",(0,o.jsx)(n.code,{children:".map()"}),"\nwith a one, key, difference that it expects the items of an iterator to be\nmapped to an ",(0,o.jsx)(n.code,{children:"Option"})," from which it ignores nothing (as in ",(0,o.jsx)(n.code,{children:"None"})," ","\ud83d\ude09",")\nand also unwraps the values from ",(0,o.jsx)(n.code,{children:"Some(\u2026)"}),"."]}),"\n"]}),"\n",(0,o.jsx)(n.h4,{id:"infinite-iterator",children:"Infinite iterator"}),"\n",(0,o.jsx)(n.p,{children:"In 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",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-rust",children:"struct 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 {\n self.i = (self.i + 1) % self.size;\n Some(self.i)\n }\n}\n"})}),"\n",(0,o.jsxs)(n.p,{children:["However 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 ",(0,o.jsx)(n.code,{children:".cycle()"})]}),"\n",(0,o.jsx)(n.p,{children:"On 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",(0,o.jsx)(n.h2,{id:"day-18-boiling-boulders",children:(0,o.jsx)(n.a,{href:"https://adventofcode.com/2022/day/18",children:"Day 18: Boiling Boulders"})}),"\n",(0,o.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,o.jsx)(n.p,{children:"Let's compute a surface area of some obsidian approximated via coordinates of\ncubes."})}),"\n",(0,o.jsx)(n.h3,{id:"solution-3",children:"Solution"}),"\n",(0,o.jsx)(n.p,{children:"This 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",(0,o.jsxs)(n.p,{children:["For 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 ",(0,o.jsx)(n.code,{children:"BTreeSet"})," relatively efficient way to do it."]}),"\n",(0,o.jsx)(n.p,{children:"However 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",(0,o.jsx)(n.h2,{id:"day-19-not-enough-minerals",children:(0,o.jsx)(n.a,{href:"https://adventofcode.com/2022/day/19",children:"Day 19: Not Enough Minerals"})}),"\n",(0,o.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,o.jsx)(n.p,{children:"Finding out the best strategy for building robots to collect geodes."})}),"\n",(0,o.jsx)(n.h3,{id:"solution-4",children:"Solution"}),"\n",(0,o.jsxs)(n.p,{children:["Not much interesting stuff to mention apart from the suggestion to never believe\nthat the default implementation given by ",(0,o.jsx)(n.code,{children:"derive"})," macro is what you want, it\ndoesn't have to be. ","\ud83d\ude04"]}),"\n",(0,o.jsx)(n.h2,{id:"day-20-grove-positioning-system",children:(0,o.jsx)(n.a,{href:"https://adventofcode.com/2022/day/20",children:"Day 20: Grove Positioning System"})}),"\n",(0,o.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,o.jsxs)(n.p,{children:["Shuffling around the ",(0,o.jsx)(n.em,{children:"circular linked list"})," to find the coordinates."]})}),"\n",(0,o.jsx)(n.p,{children:"Now, 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",(0,o.jsx)(n.h3,{id:"solution-5",children:"Solution"}),"\n",(0,o.jsxs)(n.p,{children:["I 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 ",(0,o.jsx)(n.code,{children:"Rc>"}),". In the end I failed on ",(0,o.jsx)(n.em,{children:"wrong answer"}),". I have also encountered\na rather interesting issue with ",(0,o.jsx)(n.code,{children:".borrow_mut()"})," method being used on ",(0,o.jsx)(n.code,{children:"Rc>"}),"."]}),"\n",(0,o.jsx)(n.h4,{id:"borrow_mut",children:(0,o.jsx)(n.code,{children:".borrow_mut()"})}),"\n",(0,o.jsx)(n.p,{children:"Consider the following snippet of the code (taken from the documentation):"}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-rust",children:'use 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> = 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",(0,o.jsx)(n.p,{children:"We 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",(0,o.jsx)(n.admonition,{type:"note",children:(0,o.jsxs)(n.p,{children:["It is a very primitive example for ",(0,o.jsx)(n.code,{children:"Rc>"})," and mutable borrow."]})}),"\n",(0,o.jsxs)(n.p,{children:["If you uncomment the 4th line with ",(0,o.jsx)(n.code,{children:"use std::borrow::BorrowMut;"}),", you cannot\ncompile the code anymore, because of"]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{children:" 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>>`\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",(0,o.jsxs)(n.p,{children:["It might seem ",(0,o.jsx)(n.strong,{children:"a bit"})," ridiculous. However, I got to a point where the compiler\nsuggested ",(0,o.jsx)(n.code,{children:"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",(0,o.jsxs)(n.h5,{id:"borrow_mut-on-rcrefcellt",children:[(0,o.jsx)(n.code,{children:".borrow_mut()"})," on ",(0,o.jsx)(n.code,{children:"Rc>"})]}),"\n",(0,o.jsxs)(n.p,{children:["Let's consider a variable ",(0,o.jsx)(n.code,{children:"x"})," of type ",(0,o.jsx)(n.code,{children:"Rc>"}),". What happens when you\ncall ",(0,o.jsx)(n.code,{children:".borrow_mut()"})," on it? We can look at the ",(0,o.jsx)(n.code,{children:"Rc"})," type, and\u2026 hang on! There is\nneither ",(0,o.jsx)(n.code,{children:".borrow_mut()"})," method or ",(0,o.jsx)(n.code,{children:"BorrowMut"})," trait implemented. How can we do it\nthen?"]}),"\n",(0,o.jsxs)(n.p,{children:["Let's go further and we can see that ",(0,o.jsx)(n.code,{children:"RefCell"})," implements a ",(0,o.jsx)(n.code,{children:".borrow_mut()"}),"\nmethod. OK, but how can we call it on the ",(0,o.jsx)(n.code,{children:"Rc"}),"? Easily! ",(0,o.jsx)(n.code,{children:"Rc"})," implements\n",(0,o.jsx)(n.code,{children:"Deref"})," and therefore you can call methods on ",(0,o.jsx)(n.code,{children:"Rc"})," objects as if they were\n",(0,o.jsx)(n.code,{children:"T"})," objects. If we read on ",(0,o.jsxs)(n.em,{children:[(0,o.jsx)(n.code,{children:"Deref"})," coercion"]}),", we can see the following:"]}),"\n",(0,o.jsxs)(n.blockquote,{children:["\n",(0,o.jsxs)(n.p,{children:["If ",(0,o.jsx)(n.code,{children:"T"})," implements ",(0,o.jsx)(n.code,{children:"Deref"}),", \u2026:"]}),"\n",(0,o.jsxs)(n.ul,{children:["\n",(0,o.jsx)(n.li,{children:"\u2026"}),"\n",(0,o.jsxs)(n.li,{children:[(0,o.jsx)(n.code,{children:"T"})," implicitly implements all the (immutable) methods of the type ",(0,o.jsx)(n.code,{children:"U"}),"."]}),"\n"]}),"\n"]}),"\n",(0,o.jsxs)(n.p,{children:["What is the requirement for the ",(0,o.jsx)(n.code,{children:".borrow_mut()"})," on ",(0,o.jsx)(n.code,{children:"RefCell"}),"? Well, it needs\n",(0,o.jsx)(n.code,{children:"&self"}),", so the ",(0,o.jsx)(n.code,{children:"Deref"})," implements the ",(0,o.jsx)(n.code,{children:".borrow_mut()"})," for the ",(0,o.jsx)(n.code,{children:"Rc>"}),"."]}),"\n",(0,o.jsxs)(n.h5,{id:"borrowmut-trait",children:[(0,o.jsx)(n.code,{children:"BorrowMut"})," trait"]}),"\n",(0,o.jsxs)(n.p,{children:["I have not been able to find a lot on this trait. My guess is that it provides a\nmethod instead of a syntactic sugar (",(0,o.jsx)(n.code,{children:"&mut x"}),") for the mutable borrow. And also\nit provides default implementations for the types:"]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-rust",children:"impl BorrowMut for String\n\nimpl BorrowMut for &mut T\nwhere\n T: ?Sized,\n\nimpl BorrowMut for T\nwhere\n T: ?Sized,\n\nimpl BorrowMut<[T]> for Vec\nwhere\n A: Allocator,\n\nimpl BorrowMut for Box\nwhere\n A: Allocator,\n T: ?Sized,\n\nimpl BorrowMut<[T]> for [T; N]\n"})}),"\n",(0,o.jsx)(n.h5,{id:"conflict",children:"Conflict"}),"\n",(0,o.jsxs)(n.p,{children:["Now the question is why did it break the code\u2026 My first take was that the type\n",(0,o.jsx)(n.code,{children:"Rc>"})," has some ",(0,o.jsx)(n.em,{children:"specialized"})," implementation of the ",(0,o.jsx)(n.code,{children:".borrow_mut()"})," and\nthe ",(0,o.jsx)(n.code,{children:"use"})," overrides it with the default, which is true ",(0,o.jsx)(n.strong,{children:"in a sense"}),". However\nthere is no ",(0,o.jsx)(n.em,{children:"specialized"})," implementation. Let's have a look at the trait and the\ntype signature on the ",(0,o.jsx)(n.code,{children:"RefCell"}),":"]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-rust",children:"// trait\npub trait BorrowMut: Borrow\nwhere\n Borrowed: ?Sized,\n{\n fn borrow_mut(&mut self) -> &mut Borrowed;\n}\n\n// \u2039RefCell.borrow_mut()\u203a type signature\npub fn borrow_mut(&self) -> RefMut<'_, T>\n"})}),"\n",(0,o.jsxs)(n.p,{children:["I think that we can definitely agree on the fact that ",(0,o.jsx)(n.code,{children:"RefMut<'_, T>"})," is not the\n",(0,o.jsx)(n.code,{children:"RefCell"}),"."]}),"\n",(0,o.jsxs)(n.p,{children:[(0,o.jsx)(n.strong,{children:"In my opinion"}),", ",(0,o.jsx)(n.code,{children:"RefCell"})," implements a ",(0,o.jsx)(n.strong,{children:"separate"})," ",(0,o.jsx)(n.code,{children:".borrow_mut()"})," rather\nthan implementing the interface, because it ",(0,o.jsx)(n.strong,{children:"cannot"})," satisfy the type requirements\nof the trait."]}),"\n",(0,o.jsx)(n.admonition,{type:"caution",children:(0,o.jsxs)(n.p,{children:["I wonder how are we expected to deal with this conflict, if and when, we need\nboth the ",(0,o.jsx)(n.code,{children:".borrow_mut()"})," of the trait and ",(0,o.jsx)(n.code,{children:".borrow_mut()"})," of the ",(0,o.jsx)(n.code,{children:"RefCell"}),"."]})}),"\n",(0,o.jsxs)(n.admonition,{title:"Fun fact",type:"tip",children:[(0,o.jsxs)(n.p,{children:["I was suggested by the compiler to do ",(0,o.jsx)(n.code,{children:"use std::borrow::BorrowMut;"})," and break the\ncode."]}),(0,o.jsxs)(n.p,{children:["So much for the ",(0,o.jsx)(n.em,{children:"almighty"})," and ",(0,o.jsx)(n.em,{children:"helpful"})," compiler\u2026"]})]}),"\n",(0,o.jsx)(n.h2,{id:"day-21-monkey-math",children:(0,o.jsx)(n.a,{href:"https://adventofcode.com/2022/day/21",children:"Day 21: Monkey Math"})}),"\n",(0,o.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,o.jsx)(n.p,{children:"Computing an expression tree and then also finding ideal value for a node."})}),"\n",(0,o.jsx)(n.h3,{id:"solution-6",children:"Solution"}),"\n",(0,o.jsx)(n.p,{children:"Relatively 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",(0,o.jsxs)(n.h4,{id:"default-trait",children:[(0,o.jsx)(n.code,{children:"Default"})," trait"]}),"\n",(0,o.jsxs)(n.p,{children:["For 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",(0,o.jsx)(n.sup,{children:(0,o.jsx)(n.a,{href:"#user-content-fn-1-990909",id:"user-content-fnref-1-990909","data-footnote-ref":!0,"aria-describedby":"footnote-label",children:"1"})})," that is described\nas:"]}),"\n",(0,o.jsxs)(n.blockquote,{children:["\n",(0,o.jsx)(n.p,{children:"A trait for giving a type a useful default value."}),"\n"]}),"\n",(0,o.jsxs)(n.p,{children:["I guess it sums it up nicely. The more interesting part about this is the fact\nthat you can use the ",(0,o.jsx)(n.em,{children:"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",(0,o.jsx)(n.sup,{children:(0,o.jsx)(n.a,{href:"#user-content-fn-2-990909",id:"user-content-fnref-2-990909","data-footnote-ref":!0,"aria-describedby":"footnote-label",children:"2"})}),":"]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-rust",children:"#[derive(Default)]\nenum Color {\n #[default]\n White,\n Gray,\n Black,\n}\n"})}),"\n",(0,o.jsx)(n.h4,{id:"abusing-negation",children:"Abusing negation"}),"\n",(0,o.jsxs)(n.p,{children:["If you want to use a ",(0,o.jsx)(n.em,{children:"unary minus"})," operator on your own type, you can implement\na ",(0,o.jsx)(n.code,{children:"Neg"})," trait",(0,o.jsx)(n.sup,{children:(0,o.jsx)(n.a,{href:"#user-content-fn-3-990909",id:"user-content-fnref-3-990909","data-footnote-ref":!0,"aria-describedby":"footnote-label",children:"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 ","\ud83d\ude04"]}),"\n",(0,o.jsxs)(n.section,{"data-footnotes":!0,className:"footnotes",children:[(0,o.jsx)(n.h2,{className:"sr-only",id:"footnote-label",children:"Footnotes"}),"\n",(0,o.jsxs)(n.ol,{children:["\n",(0,o.jsxs)(n.li,{id:"user-content-fn-1-990909",children:["\n",(0,o.jsxs)(n.p,{children:[(0,o.jsx)(n.a,{href:"https://doc.rust-lang.org/std/default/trait.Default.html",children:(0,o.jsx)(n.code,{children:"Default"})})," docs ",(0,o.jsx)(n.a,{href:"#user-content-fnref-1-990909","data-footnote-backref":"","aria-label":"Back to reference 1",className:"data-footnote-backref",children:"\u21a9"})]}),"\n"]}),"\n",(0,o.jsxs)(n.li,{id:"user-content-fn-2-990909",children:["\n",(0,o.jsxs)(n.p,{children:["Pardon my example from the graph algorithms ;) ",(0,o.jsx)(n.a,{href:"#user-content-fnref-2-990909","data-footnote-backref":"","aria-label":"Back to reference 2",className:"data-footnote-backref",children:"\u21a9"})]}),"\n"]}),"\n",(0,o.jsxs)(n.li,{id:"user-content-fn-3-990909",children:["\n",(0,o.jsxs)(n.p,{children:[(0,o.jsx)(n.a,{href:"https://doc.rust-lang.org/std/ops/trait.Neg.html",children:(0,o.jsx)(n.code,{children:"Neg"})})," docs ",(0,o.jsx)(n.a,{href:"#user-content-fnref-3-990909","data-footnote-backref":"","aria-label":"Back to reference 3",className:"data-footnote-backref",children:"\u21a9"})]}),"\n"]}),"\n"]}),"\n"]})]})}function h(e={}){const{wrapper:n}={...(0,i.a)(),...e.components};return n?(0,o.jsx)(n,{...e,children:(0,o.jsx)(c,{...e})}):c(e)}},11151:(e,n,t)=>{t.d(n,{Z:()=>s,a:()=>a});var o=t(67294);const i={},r=o.createContext(i);function a(e){const n=o.useContext(r);return o.useMemo((function(){return"function"==typeof e?e(n):{...n,...e}}),[n,e])}function s(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(i):e.components||i:a(e.components),o.createElement(r.Provider,{value:n},e.children)}}}]); \ No newline at end of file diff --git a/assets/js/f48be158.5e2dd98c.js b/assets/js/f48be158.5e2dd98c.js deleted file mode 100644 index e124484..0000000 --- a/assets/js/f48be158.5e2dd98c.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[4064],{12326:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>l,contentTitle:()=>a,default:()=>h,frontMatter:()=>r,metadata:()=>s,toc:()=>d});var o=t(85893),i=t(11151);const r={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:!1},a=void 0,s={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:!0,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:!1},unlisted:!1,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"}},l={authorsImageUrls:[void 0]},d=[{value:"Day 15: Beacon Exclusion Zone",id:"day-15-beacon-exclusion-zone",level:2},{value:"Solution",id:"solution",level:3},{value:"Day 16: Proboscidea Volcanium",id:"day-16-proboscidea-volcanium",level:2},{value:"Solution",id:"solution-1",level:3},{value:"Indexing in graph",id:"indexing-in-graph",level:4},{value:"Cartesian product",id:"cartesian-product",level:4},{value:"\u201cImplementing\u201d an iterator",id:"implementing-an-iterator",level:4},{value:"Day 17: Pyroclastic Flow",id:"day-17-pyroclastic-flow",level:2},{value:"Solution",id:"solution-2",level:3},{value:"Collision detection",id:"collision-detection",level:4},{value:"Infinite iterator",id:"infinite-iterator",level:4},{value:"Day 18: Boiling Boulders",id:"day-18-boiling-boulders",level:2},{value:"Solution",id:"solution-3",level:3},{value:"Day 19: Not Enough Minerals",id:"day-19-not-enough-minerals",level:2},{value:"Solution",id:"solution-4",level:3},{value:"Day 20: Grove Positioning System",id:"day-20-grove-positioning-system",level:2},{value:"Solution",id:"solution-5",level:3},{value:".borrow_mut()",id:"borrow_mut",level:4},{value:".borrow_mut() on Rc<RefCell<T>>",id:"borrow_mut-on-rcrefcellt",level:5},{value:"BorrowMut trait",id:"borrowmut-trait",level:5},{value:"Conflict",id:"conflict",level:5},{value:"Day 21: Monkey Math",id:"day-21-monkey-math",level:2},{value:"Solution",id:"solution-6",level:3},{value:"Default trait",id:"default-trait",level:4},{value:"Abusing negation",id:"abusing-negation",level:4}];function c(e){const n={a:"a",admonition:"admonition",blockquote:"blockquote",code:"code",em:"em",h2:"h2",h3:"h3",h4:"h4",h5:"h5",li:"li",ol:"ol",p:"p",pre:"pre",section:"section",strong:"strong",sup:"sup",ul:"ul",...(0,i.a)(),...e.components};return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsxs)(n.p,{children:["Let's go through the third week of ",(0,o.jsx)(n.a,{href:"https://adventofcode.com",children:(0,o.jsx)(n.em,{children:"Advent of Code"})})," in Rust."]}),"\n",(0,o.jsx)(n.h2,{id:"day-15-beacon-exclusion-zone",children:(0,o.jsx)(n.a,{href:"https://adventofcode.com/2022/day/15",children:"Day 15: Beacon Exclusion Zone"})}),"\n",(0,o.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,o.jsx)(n.p,{children:"Triangulating a distress beacon based on the information from the sensors."})}),"\n",(0,o.jsx)(n.h3,{id:"solution",children:"Solution"}),"\n",(0,o.jsx)(n.p,{children:"Relatively easy thing to implement, no major Rust issues hit."}),"\n",(0,o.jsx)(n.h2,{id:"day-16-proboscidea-volcanium",children:(0,o.jsx)(n.a,{href:"https://adventofcode.com/2022/day/16",children:"Day 16: Proboscidea Volcanium"})}),"\n",(0,o.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,o.jsx)(n.p,{children:"Finding a max flow in a graph given some time constraints."})}),"\n",(0,o.jsx)(n.h3,{id:"solution-1",children:"Solution"}),"\n",(0,o.jsx)(n.p,{children:"I have used some interesting things to implement this and make it easier for me."}),"\n",(0,o.jsx)(n.h4,{id:"indexing-in-graph",children:"Indexing in graph"}),"\n",(0,o.jsx)(n.p,{children:"I 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",(0,o.jsx)(n.p,{children:"Here you can see a rather short snippet from the solution that allows you to\n\u201cindex\u201d the graph:"}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-rust",children:"impl 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",(0,o.jsx)(n.h4,{id:"cartesian-product",children:"Cartesian product"}),"\n",(0,o.jsxs)(n.p,{children:["During the implementation I had to utilize Floyd-Warshall algorithm for finding\nthe shortest path between pairs of vertices and utilized the ",(0,o.jsx)(n.code,{children:"iproduct!"})," macro\nfrom the ",(0,o.jsx)(n.a,{href:"https://crates.io/crates/itertools",children:(0,o.jsx)(n.code,{children:"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",(0,o.jsx)(n.h4,{id:"implementing-an-iterator",children:"\u201cImplementing\u201d an iterator"}),"\n",(0,o.jsx)(n.p,{children:"For 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",(0,o.jsxs)(n.p,{children:["Being affected by ",(0,o.jsx)(n.em,{children:"functional programming brain damage"}),"\u2122\ufe0f",", I have chosen to\ndo this part by function that returns an iterator over the possible ways:"]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-rust",children:"fn pairings(\n valves: &BTreeSet,\n) -> impl Iterator, BTreeSet)> + '_ {\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",(0,o.jsx)(n.h2,{id:"day-17-pyroclastic-flow",children:(0,o.jsx)(n.a,{href:"https://adventofcode.com/2022/day/17",children:"Day 17: Pyroclastic Flow"})}),"\n",(0,o.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,o.jsx)(n.p,{children:"Simulating an autonomous Tetris where pieces get affected by a series of jets of\nhot gas."})}),"\n",(0,o.jsx)(n.h3,{id:"solution-2",children:"Solution"}),"\n",(0,o.jsxs)(n.p,{children:["Similarly to the previous day I have created some iterators ","\ud83d\ude04"]}),"\n",(0,o.jsx)(n.h4,{id:"collision-detection",children:"Collision detection"}),"\n",(0,o.jsx)(n.p,{children:"Once 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",(0,o.jsx)(n.p,{children:"To get the desired behaviour, you can just compose few smaller functions:"}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-rust",children:"fn occupied(shape: &[Vec]) -> impl Iterator + '_ {\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",(0,o.jsx)(n.p,{children:"In 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",(0,o.jsxs)(n.ul,{children:["\n",(0,o.jsxs)(n.li,{children:[(0,o.jsx)(n.code,{children:".enumerate()"})," allows us to get both the indices (coordinates) and the line\nor, later on, the character itself,"]}),"\n",(0,o.jsxs)(n.li,{children:[(0,o.jsx)(n.code,{children:".flat_map()"})," flattens the iterator, i.e. when we return another iterator,\nthey just get chained instead of iterating over iterators (which sounds pretty\ndisturbing, doesn't it?),"]}),"\n",(0,o.jsxs)(n.li,{children:["and finally ",(0,o.jsx)(n.code,{children:".filter_map()"})," which is pretty similar to the \u201cbasic\u201d ",(0,o.jsx)(n.code,{children:".map()"}),"\nwith a one, key, difference that it expects the items of an iterator to be\nmapped to an ",(0,o.jsx)(n.code,{children:"Option"})," from which it ignores nothing (as in ",(0,o.jsx)(n.code,{children:"None"})," ","\ud83d\ude09",")\nand also unwraps the values from ",(0,o.jsx)(n.code,{children:"Some(\u2026)"}),"."]}),"\n"]}),"\n",(0,o.jsx)(n.h4,{id:"infinite-iterator",children:"Infinite iterator"}),"\n",(0,o.jsx)(n.p,{children:"In 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",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-rust",children:"struct 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 {\n self.i = (self.i + 1) % self.size;\n Some(self.i)\n }\n}\n"})}),"\n",(0,o.jsxs)(n.p,{children:["However 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 ",(0,o.jsx)(n.code,{children:".cycle()"})]}),"\n",(0,o.jsx)(n.p,{children:"On 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",(0,o.jsx)(n.h2,{id:"day-18-boiling-boulders",children:(0,o.jsx)(n.a,{href:"https://adventofcode.com/2022/day/18",children:"Day 18: Boiling Boulders"})}),"\n",(0,o.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,o.jsx)(n.p,{children:"Let's compute a surface area of some obsidian approximated via coordinates of\ncubes."})}),"\n",(0,o.jsx)(n.h3,{id:"solution-3",children:"Solution"}),"\n",(0,o.jsx)(n.p,{children:"This 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",(0,o.jsxs)(n.p,{children:["For 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 ",(0,o.jsx)(n.code,{children:"BTreeSet"})," relatively efficient way to do it."]}),"\n",(0,o.jsx)(n.p,{children:"However 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",(0,o.jsx)(n.h2,{id:"day-19-not-enough-minerals",children:(0,o.jsx)(n.a,{href:"https://adventofcode.com/2022/day/19",children:"Day 19: Not Enough Minerals"})}),"\n",(0,o.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,o.jsx)(n.p,{children:"Finding out the best strategy for building robots to collect geodes."})}),"\n",(0,o.jsx)(n.h3,{id:"solution-4",children:"Solution"}),"\n",(0,o.jsxs)(n.p,{children:["Not much interesting stuff to mention apart from the suggestion to never believe\nthat the default implementation given by ",(0,o.jsx)(n.code,{children:"derive"})," macro is what you want, it\ndoesn't have to be. ","\ud83d\ude04"]}),"\n",(0,o.jsx)(n.h2,{id:"day-20-grove-positioning-system",children:(0,o.jsx)(n.a,{href:"https://adventofcode.com/2022/day/20",children:"Day 20: Grove Positioning System"})}),"\n",(0,o.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,o.jsxs)(n.p,{children:["Shuffling around the ",(0,o.jsx)(n.em,{children:"circular linked list"})," to find the coordinates."]})}),"\n",(0,o.jsx)(n.p,{children:"Now, 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",(0,o.jsx)(n.h3,{id:"solution-5",children:"Solution"}),"\n",(0,o.jsxs)(n.p,{children:["I 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 ",(0,o.jsx)(n.code,{children:"Rc>"}),". In the end I failed on ",(0,o.jsx)(n.em,{children:"wrong answer"}),". I have also encountered\na rather interesting issue with ",(0,o.jsx)(n.code,{children:".borrow_mut()"})," method being used on ",(0,o.jsx)(n.code,{children:"Rc>"}),"."]}),"\n",(0,o.jsx)(n.h4,{id:"borrow_mut",children:(0,o.jsx)(n.code,{children:".borrow_mut()"})}),"\n",(0,o.jsx)(n.p,{children:"Consider the following snippet of the code (taken from the documentation):"}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-rust",children:'use 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> = 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",(0,o.jsx)(n.p,{children:"We 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",(0,o.jsx)(n.admonition,{type:"note",children:(0,o.jsxs)(n.p,{children:["It is a very primitive example for ",(0,o.jsx)(n.code,{children:"Rc>"})," and mutable borrow."]})}),"\n",(0,o.jsxs)(n.p,{children:["If you uncomment the 4th line with ",(0,o.jsx)(n.code,{children:"use std::borrow::BorrowMut;"}),", you cannot\ncompile the code anymore, because of"]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{children:" 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>>`\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",(0,o.jsxs)(n.p,{children:["It might seem ",(0,o.jsx)(n.strong,{children:"a bit"})," ridiculous. However, I got to a point where the compiler\nsuggested ",(0,o.jsx)(n.code,{children:"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",(0,o.jsxs)(n.h5,{id:"borrow_mut-on-rcrefcellt",children:[(0,o.jsx)(n.code,{children:".borrow_mut()"})," on ",(0,o.jsx)(n.code,{children:"Rc>"})]}),"\n",(0,o.jsxs)(n.p,{children:["Let's consider a variable ",(0,o.jsx)(n.code,{children:"x"})," of type ",(0,o.jsx)(n.code,{children:"Rc>"}),". What happens when you\ncall ",(0,o.jsx)(n.code,{children:".borrow_mut()"})," on it? We can look at the ",(0,o.jsx)(n.code,{children:"Rc"})," type, and\u2026 hang on! There is\nneither ",(0,o.jsx)(n.code,{children:".borrow_mut()"})," method or ",(0,o.jsx)(n.code,{children:"BorrowMut"})," trait implemented. How can we do it\nthen?"]}),"\n",(0,o.jsxs)(n.p,{children:["Let's go further and we can see that ",(0,o.jsx)(n.code,{children:"RefCell"})," implements a ",(0,o.jsx)(n.code,{children:".borrow_mut()"}),"\nmethod. OK, but how can we call it on the ",(0,o.jsx)(n.code,{children:"Rc"}),"? Easily! ",(0,o.jsx)(n.code,{children:"Rc"})," implements\n",(0,o.jsx)(n.code,{children:"Deref"})," and therefore you can call methods on ",(0,o.jsx)(n.code,{children:"Rc"})," objects as if they were\n",(0,o.jsx)(n.code,{children:"T"})," objects. If we read on ",(0,o.jsxs)(n.em,{children:[(0,o.jsx)(n.code,{children:"Deref"})," coercion"]}),", we can see the following:"]}),"\n",(0,o.jsxs)(n.blockquote,{children:["\n",(0,o.jsxs)(n.p,{children:["If ",(0,o.jsx)(n.code,{children:"T"})," implements ",(0,o.jsx)(n.code,{children:"Deref"}),", \u2026:"]}),"\n",(0,o.jsxs)(n.ul,{children:["\n",(0,o.jsx)(n.li,{children:"\u2026"}),"\n",(0,o.jsxs)(n.li,{children:[(0,o.jsx)(n.code,{children:"T"})," implicitly implements all the (immutable) methods of the type ",(0,o.jsx)(n.code,{children:"U"}),"."]}),"\n"]}),"\n"]}),"\n",(0,o.jsxs)(n.p,{children:["What is the requirement for the ",(0,o.jsx)(n.code,{children:".borrow_mut()"})," on ",(0,o.jsx)(n.code,{children:"RefCell"}),"? Well, it needs\n",(0,o.jsx)(n.code,{children:"&self"}),", so the ",(0,o.jsx)(n.code,{children:"Deref"})," implements the ",(0,o.jsx)(n.code,{children:".borrow_mut()"})," for the ",(0,o.jsx)(n.code,{children:"Rc>"}),"."]}),"\n",(0,o.jsxs)(n.h5,{id:"borrowmut-trait",children:[(0,o.jsx)(n.code,{children:"BorrowMut"})," trait"]}),"\n",(0,o.jsxs)(n.p,{children:["I have not been able to find a lot on this trait. My guess is that it provides a\nmethod instead of a syntactic sugar (",(0,o.jsx)(n.code,{children:"&mut x"}),") for the mutable borrow. And also\nit provides default implementations for the types:"]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-rust",children:"impl BorrowMut for String\n\nimpl BorrowMut for &mut T\nwhere\n T: ?Sized,\n\nimpl BorrowMut for T\nwhere\n T: ?Sized,\n\nimpl BorrowMut<[T]> for Vec\nwhere\n A: Allocator,\n\nimpl BorrowMut for Box\nwhere\n A: Allocator,\n T: ?Sized,\n\nimpl BorrowMut<[T]> for [T; N]\n"})}),"\n",(0,o.jsx)(n.h5,{id:"conflict",children:"Conflict"}),"\n",(0,o.jsxs)(n.p,{children:["Now the question is why did it break the code\u2026 My first take was that the type\n",(0,o.jsx)(n.code,{children:"Rc>"})," has some ",(0,o.jsx)(n.em,{children:"specialized"})," implementation of the ",(0,o.jsx)(n.code,{children:".borrow_mut()"})," and\nthe ",(0,o.jsx)(n.code,{children:"use"})," overrides it with the default, which is true ",(0,o.jsx)(n.strong,{children:"in a sense"}),". However\nthere is no ",(0,o.jsx)(n.em,{children:"specialized"})," implementation. Let's have a look at the trait and the\ntype signature on the ",(0,o.jsx)(n.code,{children:"RefCell"}),":"]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-rust",children:"// trait\npub trait BorrowMut: Borrow\nwhere\n Borrowed: ?Sized,\n{\n fn borrow_mut(&mut self) -> &mut Borrowed;\n}\n\n// \u2039RefCell.borrow_mut()\u203a type signature\npub fn borrow_mut(&self) -> RefMut<'_, T>\n"})}),"\n",(0,o.jsxs)(n.p,{children:["I think that we can definitely agree on the fact that ",(0,o.jsx)(n.code,{children:"RefMut<'_, T>"})," is not the\n",(0,o.jsx)(n.code,{children:"RefCell"}),"."]}),"\n",(0,o.jsxs)(n.p,{children:[(0,o.jsx)(n.strong,{children:"In my opinion"}),", ",(0,o.jsx)(n.code,{children:"RefCell"})," implements a ",(0,o.jsx)(n.strong,{children:"separate"})," ",(0,o.jsx)(n.code,{children:".borrow_mut()"})," rather\nthan implementing the interface, because it ",(0,o.jsx)(n.strong,{children:"cannot"})," satisfy the type requirements\nof the trait."]}),"\n",(0,o.jsx)(n.admonition,{type:"caution",children:(0,o.jsxs)(n.p,{children:["I wonder how are we expected to deal with this conflict, if and when, we need\nboth the ",(0,o.jsx)(n.code,{children:".borrow_mut()"})," of the trait and ",(0,o.jsx)(n.code,{children:".borrow_mut()"})," of the ",(0,o.jsx)(n.code,{children:"RefCell"}),"."]})}),"\n",(0,o.jsxs)(n.admonition,{title:"Fun fact",type:"tip",children:[(0,o.jsxs)(n.p,{children:["I was suggested by the compiler to do ",(0,o.jsx)(n.code,{children:"use std::borrow::BorrowMut;"})," and break the\ncode."]}),(0,o.jsxs)(n.p,{children:["So much for the ",(0,o.jsx)(n.em,{children:"almighty"})," and ",(0,o.jsx)(n.em,{children:"helpful"})," compiler\u2026"]})]}),"\n",(0,o.jsx)(n.h2,{id:"day-21-monkey-math",children:(0,o.jsx)(n.a,{href:"https://adventofcode.com/2022/day/21",children:"Day 21: Monkey Math"})}),"\n",(0,o.jsx)(n.admonition,{title:"tl;dr",type:"info",children:(0,o.jsx)(n.p,{children:"Computing an expression tree and then also finding ideal value for a node."})}),"\n",(0,o.jsx)(n.h3,{id:"solution-6",children:"Solution"}),"\n",(0,o.jsx)(n.p,{children:"Relatively 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",(0,o.jsxs)(n.h4,{id:"default-trait",children:[(0,o.jsx)(n.code,{children:"Default"})," trait"]}),"\n",(0,o.jsxs)(n.p,{children:["For 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",(0,o.jsx)(n.sup,{children:(0,o.jsx)(n.a,{href:"#user-content-fn-1-990909",id:"user-content-fnref-1-990909","data-footnote-ref":!0,"aria-describedby":"footnote-label",children:"1"})})," that is described\nas:"]}),"\n",(0,o.jsxs)(n.blockquote,{children:["\n",(0,o.jsx)(n.p,{children:"A trait for giving a type a useful default value."}),"\n"]}),"\n",(0,o.jsxs)(n.p,{children:["I guess it sums it up nicely. The more interesting part about this is the fact\nthat you can use the ",(0,o.jsx)(n.em,{children:"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",(0,o.jsx)(n.sup,{children:(0,o.jsx)(n.a,{href:"#user-content-fn-2-990909",id:"user-content-fnref-2-990909","data-footnote-ref":!0,"aria-describedby":"footnote-label",children:"2"})}),":"]}),"\n",(0,o.jsx)(n.pre,{children:(0,o.jsx)(n.code,{className:"language-rust",children:"#[derive(Default)]\nenum Color {\n #[default]\n White,\n Gray,\n Black,\n}\n"})}),"\n",(0,o.jsx)(n.h4,{id:"abusing-negation",children:"Abusing negation"}),"\n",(0,o.jsxs)(n.p,{children:["If you want to use a ",(0,o.jsx)(n.em,{children:"unary minus"})," operator on your own type, you can implement\na ",(0,o.jsx)(n.code,{children:"Neg"})," trait",(0,o.jsx)(n.sup,{children:(0,o.jsx)(n.a,{href:"#user-content-fn-3-990909",id:"user-content-fnref-3-990909","data-footnote-ref":!0,"aria-describedby":"footnote-label",children:"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 ","\ud83d\ude04"]}),"\n",(0,o.jsxs)(n.section,{"data-footnotes":!0,className:"footnotes",children:[(0,o.jsx)(n.h2,{className:"sr-only",id:"footnote-label",children:"Footnotes"}),"\n",(0,o.jsxs)(n.ol,{children:["\n",(0,o.jsxs)(n.li,{id:"user-content-fn-1-990909",children:["\n",(0,o.jsxs)(n.p,{children:[(0,o.jsx)(n.a,{href:"https://doc.rust-lang.org/std/default/trait.Default.html",children:(0,o.jsx)(n.code,{children:"Default"})})," docs ",(0,o.jsx)(n.a,{href:"#user-content-fnref-1-990909","data-footnote-backref":"","aria-label":"Back to reference 1",className:"data-footnote-backref",children:"\u21a9"})]}),"\n"]}),"\n",(0,o.jsxs)(n.li,{id:"user-content-fn-2-990909",children:["\n",(0,o.jsxs)(n.p,{children:["Pardon my example from the graph algorithms ;) ",(0,o.jsx)(n.a,{href:"#user-content-fnref-2-990909","data-footnote-backref":"","aria-label":"Back to reference 2",className:"data-footnote-backref",children:"\u21a9"})]}),"\n"]}),"\n",(0,o.jsxs)(n.li,{id:"user-content-fn-3-990909",children:["\n",(0,o.jsxs)(n.p,{children:[(0,o.jsx)(n.a,{href:"https://doc.rust-lang.org/std/ops/trait.Neg.html",children:(0,o.jsx)(n.code,{children:"Neg"})})," docs ",(0,o.jsx)(n.a,{href:"#user-content-fnref-3-990909","data-footnote-backref":"","aria-label":"Back to reference 3",className:"data-footnote-backref",children:"\u21a9"})]}),"\n"]}),"\n"]}),"\n"]})]})}function h(e={}){const{wrapper:n}={...(0,i.a)(),...e.components};return n?(0,o.jsx)(n,{...e,children:(0,o.jsx)(c,{...e})}):c(e)}},11151:(e,n,t)=>{t.d(n,{Z:()=>s,a:()=>a});var o=t(67294);const i={},r=o.createContext(i);function a(e){const n=o.useContext(r);return o.useMemo((function(){return"function"==typeof e?e(n):{...n,...e}}),[n,e])}function s(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(i):e.components||i:a(e.components),o.createElement(r.Provider,{value:n},e.children)}}}]); \ No newline at end of file diff --git a/assets/js/runtime~main.65095f6f.js b/assets/js/runtime~main.3f39a938.js similarity index 91% rename from assets/js/runtime~main.65095f6f.js rename to assets/js/runtime~main.3f39a938.js index ac0236b..cbd6c35 100644 --- a/assets/js/runtime~main.65095f6f.js +++ b/assets/js/runtime~main.3f39a938.js @@ -1 +1 @@ -(()=>{"use strict";var e,a,c,f,d={},b={};function t(e){var a=b[e];if(void 0!==a)return a.exports;var c=b[e]={exports:{}};return d[e].call(c.exports,c,c.exports,t),c.exports}t.m=d,e=[],t.O=(a,c,f,d)=>{if(!c){var b=1/0;for(i=0;i=d)&&Object.keys(t.O).every((e=>t.O[e](c[o])))?c.splice(o--,1):(r=!1,d0&&e[i-1][2]>d;i--)e[i]=e[i-1];e[i]=[c,f,d]},t.n=e=>{var a=e&&e.__esModule?()=>e.default:()=>e;return t.d(a,{a:a}),a},c=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,t.t=function(e,f){if(1&f&&(e=this(e)),8&f)return e;if("object"==typeof e&&e){if(4&f&&e.__esModule)return e;if(16&f&&"function"==typeof e.then)return e}var d=Object.create(null);t.r(d);var b={};a=a||[null,c({}),c([]),c(c)];for(var r=2&f&&e;"object"==typeof r&&!~a.indexOf(r);r=c(r))Object.getOwnPropertyNames(r).forEach((a=>b[a]=()=>e[a]));return b.default=()=>e,t.d(d,b),d},t.d=(e,a)=>{for(var c in a)t.o(a,c)&&!t.o(e,c)&&Object.defineProperty(e,c,{enumerable:!0,get:a[c]})},t.f={},t.e=e=>Promise.all(Object.keys(t.f).reduce(((a,c)=>(t.f[c](e,a),a)),[])),t.u=e=>"assets/js/"+({59:"b1288602",115:"30814625",146:"dff2ebad",281:"2ca64e35",354:"bc0c9d90",494:"1a606400",569:"ddc7679f",635:"c4c4056e",655:"9a3dc578",728:"686a7a89",822:"8c0e532b",866:"4200b1a9",1011:"377f3aa1",1050:"a7098721",1145:"947341b7",1171:"d7f7fb17",1235:"86cd1460",1378:"0220f5fc",1464:"97a42631",1475:"e1d2ae23",1492:"d4b1e057",1494:"16cbc838",1547:"1cd58e77",1648:"48b268a6",1851:"0fcbc6ca",1885:"84d1e0d8",1960:"e31003e9",2125:"06c4a8fc",2177:"3da4b779",2210:"9df0e937",2264:"962da50c",2433:"b5a32f14",2445:"decbf9d1",2482:"dd841e73",2545:"9b91a88c",2606:"08dfa3a2",2741:"d675395f",2997:"d8f4410e",3039:"765ea78b",3086:"cfa2b263",3089:"a6aa9e1f",3184:"7e6d325b",3220:"34ab65f4",3276:"6e3cbca1",3388:"29694455",3519:"4621632b",3561:"95b96bb9",3608:"9e4087bc",3618:"a6a48ea2",3707:"24fecc0a",3713:"698e2076",3731:"087808f1",3734:"0123bc76",3751:"3720c009",3803:"794ef108",3887:"933b95b3",3979:"2af5d0a7",4013:"01a85c17",4064:"f48be158",4195:"c4f5d8e4",4256:"75cccf44",4269:"0bfe45d5",4327:"4e546705",4343:"df0885f0",4368:"a94703ab",4382:"a4c10cf4",4394:"51624505",4562:"976c4f3b",4637:"19d7c045",4638:"2fcf0558",5169:"d79dd549",5287:"6bc697d0",5376:"1535ede8",5430:"52f2a5bf",5521:"9287eafd",5634:"595c7293",5658:"af8b72a7",5701:"3adcbc3a",5775:"8e6bb954",5824:"a80747a0",5934:"f75910c4",5975:"4edd2021",6064:"7ce7faac",6097:"b0291f37",6103:"ccc49370",6179:"d57b4369",6292:"d255bd7f",6306:"4f96b16e",6327:"fb4361d3",6342:"2b89902a",6435:"28d80ff8",6519:"bc2d22bc",6544:"d05e838c",6573:"c580b66a",6864:"bb984793",6890:"22a175ec",7084:"45c9e308",7257:"aa24fd5d",7292:"493c0536",7438:"b8cbf382",7568:"0608d96f",7728:"8a25f659",7743:"df078f58",7755:"ab2721d4",7918:"17896441",7920:"1a4e3797",7926:"3011a4c0",8058:"520f8175",8091:"bb882650",8236:"3d92ba6e",8289:"a2ba8888",8326:"15966941",8387:"eba2374c",8472:"ff82dde7",8480:"8b1802c5",8518:"a7bd4aaa",8520:"62d847b3",8529:"1acf65cc",8610:"6875c492",8643:"ff472cd9",8757:"e89da83e",8786:"a082abd3",8807:"dead8108",8908:"d309b5b1",9066:"8d31a880",9173:"5ca803d2",9179:"b9f7f5c4",9197:"b25fbc58",9228:"66d5ef6c",9249:"70a4540f",9300:"146d9b84",9385:"95f41f0b",9414:"354a7b72",9579:"5c15401e",9661:"5e95c892",9679:"b45dccf0",9731:"7052c0bc",9771:"534d4833",9817:"14eb3368",9898:"0178f9ad",9924:"df203c0f"}[e]||e)+"."+{59:"2a7bb9cd",109:"192a1082",115:"1cb0ad07",130:"b07e32e5",132:"6eeb92f1",146:"2596a554",240:"962c2c3a",281:"e4c24d50",354:"22532279",494:"9499d809",569:"4b5bdacd",635:"3de7285f",655:"07cb1f6c",728:"ebbeda14",822:"8df94607",866:"faadd2c9",1011:"4ebbc06f",1050:"33f429e4",1145:"06e92a4d",1171:"3796c0b9",1235:"f549d2c3",1325:"f9a9e4dd",1378:"6bd42e59",1426:"b2a3e78b",1464:"7eff63e9",1475:"2bc6580d",1492:"c26d5bb6",1494:"eafc393a",1504:"972c6306",1547:"4b0ee92c",1644:"e1df3952",1648:"56c72f30",1763:"dd6ac9f1",1772:"e7125761",1851:"73a3a140",1885:"e078634a",1960:"e9396e0a",2125:"18eb9afc",2177:"1354e52a",2183:"695e6dce",2210:"2c53d1aa",2264:"ea10811e",2433:"68cedca8",2445:"369aa5a6",2482:"c1ec5d72",2545:"5685ebf2",2606:"0462ec4c",2661:"adb036a5",2693:"86767de9",2696:"9c4ce6ae",2700:"eb54ab23",2741:"1f389aac",2997:"e8838bb3",3039:"29a37caf",3076:"0d102429",3086:"efd5103c",3089:"305accbe",3184:"0dc3275f",3220:"5fa3179c",3276:"5d0620d6",3343:"c68ed9e0",3388:"5fa079ce",3519:"bd86e6e4",3561:"f1e9070e",3608:"c1ded62d",3618:"7749d78c",3619:"169a66d1",3707:"0d18355b",3713:"0fda5cee",3731:"0a5fb140",3734:"d7742152",3751:"9d2dcf9d",3803:"5b256546",3887:"6eeb49bf",3979:"928c2eb4",4013:"9b387ded",4064:"5e2dd98c",4195:"b182cb1f",4238:"732f7e6d",4256:"b0cfb80e",4269:"143f3da4",4327:"40303d4d",4343:"2970a5ee",4368:"efd630be",4382:"e91bee7a",4394:"60fbe3b9",4562:"cfe53f32",4637:"fd298b3d",4638:"a6f753b6",4706:"bf286a6c",5169:"0ed0fe01",5269:"a9818fb6",5287:"410760a1",5326:"480380dd",5376:"102142f5",5430:"839d7f40",5521:"7613dea7",5634:"6c273bef",5658:"37a3aa6c",5701:"481c535c",5775:"4d6706b7",5790:"a9566ed9",5824:"b21945df",5934:"750e8d79",5943:"ebdacf10",5975:"ba1a6e92",6064:"fd0f7c12",6097:"5b91d377",6103:"78004ce5",6179:"6f772ce2",6255:"4bb462ce",6292:"da5efa5d",6306:"072f92b8",6327:"b6ca83b5",6342:"5cec8345",6435:"b8c94f5a",6519:"974fe1a5",6544:"3caaf7e6",6573:"aa8d7117",6648:"7d3c04e0",6864:"22b3e630",6890:"504e3826",6945:"1665fd21",6985:"b22ddd47",7084:"57b8321c",7257:"e4465696",7292:"6ae62548",7438:"e3b79fad",7568:"a18c3650",7728:"6cbfa670",7743:"4f109cb4",7755:"6fad72ba",7918:"2ef23eb3",7920:"3807d38b",7926:"bfa0084e",7936:"da5208cb",8016:"f7e4e334",8058:"d9b4c84f",8091:"6eee4002",8236:"e64b02a7",8289:"ab09cb54",8326:"58ddb6d9",8387:"dcc463b2",8472:"c32d56e5",8480:"408315a3",8518:"69e4c2b5",8520:"ea246a7d",8529:"33171995",8610:"5be02386",8643:"a09aa523",8757:"1856d5b6",8786:"6458a62f",8807:"9d966504",8894:"bbb1746a",8908:"924b0302",8955:"88257d8a",9066:"e6f69b2d",9138:"e5753066",9173:"986e22d4",9179:"8dd00486",9197:"90e65bfc",9228:"fc107ca5",9249:"312c2807",9300:"bdf83d64",9385:"b012cd5f",9414:"becd0640",9579:"e4b1c753",9661:"8ef24486",9679:"7ab0cc2a",9731:"54d577f1",9771:"162e2ecd",9817:"1936981e",9893:"04fdeb2a",9898:"568886e5",9924:"a5b6acbb"}[e]+".js",t.miniCssF=e=>{},t.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),t.o=(e,a)=>Object.prototype.hasOwnProperty.call(e,a),f={},t.l=(e,a,c,d)=>{if(f[e])f[e].push(a);else{var b,r;if(void 0!==c)for(var o=document.getElementsByTagName("script"),n=0;n{b.onerror=b.onload=null,clearTimeout(l);var d=f[e];if(delete f[e],b.parentNode&&b.parentNode.removeChild(b),d&&d.forEach((e=>e(c))),a)return a(c)},l=setTimeout(u.bind(null,void 0,{type:"timeout",target:b}),12e4);b.onerror=u.bind(null,b.onerror),b.onload=u.bind(null,b.onload),r&&document.head.appendChild(b)}},t.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.p="/",t.gca=function(e){return e={15966941:"8326",17896441:"7918",29694455:"3388",30814625:"115",51624505:"4394",b1288602:"59",dff2ebad:"146","2ca64e35":"281",bc0c9d90:"354","1a606400":"494",ddc7679f:"569",c4c4056e:"635","9a3dc578":"655","686a7a89":"728","8c0e532b":"822","4200b1a9":"866","377f3aa1":"1011",a7098721:"1050","947341b7":"1145",d7f7fb17:"1171","86cd1460":"1235","0220f5fc":"1378","97a42631":"1464",e1d2ae23:"1475",d4b1e057:"1492","16cbc838":"1494","1cd58e77":"1547","48b268a6":"1648","0fcbc6ca":"1851","84d1e0d8":"1885",e31003e9:"1960","06c4a8fc":"2125","3da4b779":"2177","9df0e937":"2210","962da50c":"2264",b5a32f14:"2433",decbf9d1:"2445",dd841e73:"2482","9b91a88c":"2545","08dfa3a2":"2606",d675395f:"2741",d8f4410e:"2997","765ea78b":"3039",cfa2b263:"3086",a6aa9e1f:"3089","7e6d325b":"3184","34ab65f4":"3220","6e3cbca1":"3276","4621632b":"3519","95b96bb9":"3561","9e4087bc":"3608",a6a48ea2:"3618","24fecc0a":"3707","698e2076":"3713","087808f1":"3731","0123bc76":"3734","3720c009":"3751","794ef108":"3803","933b95b3":"3887","2af5d0a7":"3979","01a85c17":"4013",f48be158:"4064",c4f5d8e4:"4195","75cccf44":"4256","0bfe45d5":"4269","4e546705":"4327",df0885f0:"4343",a94703ab:"4368",a4c10cf4:"4382","976c4f3b":"4562","19d7c045":"4637","2fcf0558":"4638",d79dd549:"5169","6bc697d0":"5287","1535ede8":"5376","52f2a5bf":"5430","9287eafd":"5521","595c7293":"5634",af8b72a7:"5658","3adcbc3a":"5701","8e6bb954":"5775",a80747a0:"5824",f75910c4:"5934","4edd2021":"5975","7ce7faac":"6064",b0291f37:"6097",ccc49370:"6103",d57b4369:"6179",d255bd7f:"6292","4f96b16e":"6306",fb4361d3:"6327","2b89902a":"6342","28d80ff8":"6435",bc2d22bc:"6519",d05e838c:"6544",c580b66a:"6573",bb984793:"6864","22a175ec":"6890","45c9e308":"7084",aa24fd5d:"7257","493c0536":"7292",b8cbf382:"7438","0608d96f":"7568","8a25f659":"7728",df078f58:"7743",ab2721d4:"7755","1a4e3797":"7920","3011a4c0":"7926","520f8175":"8058",bb882650:"8091","3d92ba6e":"8236",a2ba8888:"8289",eba2374c:"8387",ff82dde7:"8472","8b1802c5":"8480",a7bd4aaa:"8518","62d847b3":"8520","1acf65cc":"8529","6875c492":"8610",ff472cd9:"8643",e89da83e:"8757",a082abd3:"8786",dead8108:"8807",d309b5b1:"8908","8d31a880":"9066","5ca803d2":"9173",b9f7f5c4:"9179",b25fbc58:"9197","66d5ef6c":"9228","70a4540f":"9249","146d9b84":"9300","95f41f0b":"9385","354a7b72":"9414","5c15401e":"9579","5e95c892":"9661",b45dccf0:"9679","7052c0bc":"9731","534d4833":"9771","14eb3368":"9817","0178f9ad":"9898",df203c0f:"9924"}[e]||e,t.p+t.u(e)},(()=>{var e={1303:0,532:0};t.f.j=(a,c)=>{var f=t.o(e,a)?e[a]:void 0;if(0!==f)if(f)c.push(f[2]);else if(/^(1303|532)$/.test(a))e[a]=0;else{var d=new Promise(((c,d)=>f=e[a]=[c,d]));c.push(f[2]=d);var b=t.p+t.u(a),r=new Error;t.l(b,(c=>{if(t.o(e,a)&&(0!==(f=e[a])&&(e[a]=void 0),f)){var d=c&&("load"===c.type?"missing":c.type),b=c&&c.target&&c.target.src;r.message="Loading chunk "+a+" failed.\n("+d+": "+b+")",r.name="ChunkLoadError",r.type=d,r.request=b,f[1](r)}}),"chunk-"+a,a)}},t.O.j=a=>0===e[a];var a=(a,c)=>{var f,d,b=c[0],r=c[1],o=c[2],n=0;if(b.some((a=>0!==e[a]))){for(f in r)t.o(r,f)&&(t.m[f]=r[f]);if(o)var i=o(t)}for(a&&a(c);n{"use strict";var e,a,c,f,d={},b={};function t(e){var a=b[e];if(void 0!==a)return a.exports;var c=b[e]={exports:{}};return d[e].call(c.exports,c,c.exports,t),c.exports}t.m=d,e=[],t.O=(a,c,f,d)=>{if(!c){var b=1/0;for(i=0;i=d)&&Object.keys(t.O).every((e=>t.O[e](c[o])))?c.splice(o--,1):(r=!1,d0&&e[i-1][2]>d;i--)e[i]=e[i-1];e[i]=[c,f,d]},t.n=e=>{var a=e&&e.__esModule?()=>e.default:()=>e;return t.d(a,{a:a}),a},c=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,t.t=function(e,f){if(1&f&&(e=this(e)),8&f)return e;if("object"==typeof e&&e){if(4&f&&e.__esModule)return e;if(16&f&&"function"==typeof e.then)return e}var d=Object.create(null);t.r(d);var b={};a=a||[null,c({}),c([]),c(c)];for(var r=2&f&&e;"object"==typeof r&&!~a.indexOf(r);r=c(r))Object.getOwnPropertyNames(r).forEach((a=>b[a]=()=>e[a]));return b.default=()=>e,t.d(d,b),d},t.d=(e,a)=>{for(var c in a)t.o(a,c)&&!t.o(e,c)&&Object.defineProperty(e,c,{enumerable:!0,get:a[c]})},t.f={},t.e=e=>Promise.all(Object.keys(t.f).reduce(((a,c)=>(t.f[c](e,a),a)),[])),t.u=e=>"assets/js/"+({59:"b1288602",115:"30814625",146:"dff2ebad",281:"2ca64e35",354:"bc0c9d90",494:"1a606400",569:"ddc7679f",635:"c4c4056e",655:"9a3dc578",728:"686a7a89",822:"8c0e532b",866:"4200b1a9",1011:"377f3aa1",1050:"a7098721",1145:"947341b7",1171:"d7f7fb17",1235:"86cd1460",1378:"0220f5fc",1464:"97a42631",1475:"e1d2ae23",1492:"d4b1e057",1494:"16cbc838",1547:"1cd58e77",1648:"48b268a6",1851:"0fcbc6ca",1885:"84d1e0d8",1960:"e31003e9",2125:"06c4a8fc",2177:"3da4b779",2210:"9df0e937",2264:"962da50c",2433:"b5a32f14",2445:"decbf9d1",2482:"dd841e73",2545:"9b91a88c",2606:"08dfa3a2",2741:"d675395f",2997:"d8f4410e",3039:"765ea78b",3086:"cfa2b263",3089:"a6aa9e1f",3184:"7e6d325b",3220:"34ab65f4",3276:"6e3cbca1",3388:"29694455",3519:"4621632b",3561:"95b96bb9",3608:"9e4087bc",3618:"a6a48ea2",3707:"24fecc0a",3713:"698e2076",3731:"087808f1",3734:"0123bc76",3751:"3720c009",3803:"794ef108",3887:"933b95b3",3979:"2af5d0a7",4013:"01a85c17",4064:"f48be158",4195:"c4f5d8e4",4256:"75cccf44",4269:"0bfe45d5",4327:"4e546705",4343:"df0885f0",4368:"a94703ab",4382:"a4c10cf4",4394:"51624505",4562:"976c4f3b",4637:"19d7c045",4638:"2fcf0558",5169:"d79dd549",5287:"6bc697d0",5376:"1535ede8",5430:"52f2a5bf",5521:"9287eafd",5634:"595c7293",5658:"af8b72a7",5701:"3adcbc3a",5775:"8e6bb954",5824:"a80747a0",5934:"f75910c4",5975:"4edd2021",6064:"7ce7faac",6097:"b0291f37",6103:"ccc49370",6179:"d57b4369",6292:"d255bd7f",6306:"4f96b16e",6327:"fb4361d3",6342:"2b89902a",6435:"28d80ff8",6519:"bc2d22bc",6544:"d05e838c",6573:"c580b66a",6864:"bb984793",6890:"22a175ec",7084:"45c9e308",7257:"aa24fd5d",7292:"493c0536",7438:"b8cbf382",7568:"0608d96f",7728:"8a25f659",7743:"df078f58",7755:"ab2721d4",7918:"17896441",7920:"1a4e3797",7926:"3011a4c0",8058:"520f8175",8091:"bb882650",8236:"3d92ba6e",8289:"a2ba8888",8326:"15966941",8387:"eba2374c",8472:"ff82dde7",8480:"8b1802c5",8518:"a7bd4aaa",8520:"62d847b3",8529:"1acf65cc",8610:"6875c492",8643:"ff472cd9",8757:"e89da83e",8786:"a082abd3",8807:"dead8108",8908:"d309b5b1",9066:"8d31a880",9173:"5ca803d2",9179:"b9f7f5c4",9197:"b25fbc58",9228:"66d5ef6c",9249:"70a4540f",9300:"146d9b84",9385:"95f41f0b",9414:"354a7b72",9579:"5c15401e",9661:"5e95c892",9679:"b45dccf0",9731:"7052c0bc",9771:"534d4833",9817:"14eb3368",9898:"0178f9ad",9924:"df203c0f"}[e]||e)+"."+{59:"fa264713",109:"192a1082",115:"1cb0ad07",130:"b07e32e5",132:"6eeb92f1",146:"26aca592",240:"962c2c3a",281:"e4c24d50",354:"22532279",494:"9499d809",569:"4b5bdacd",635:"a7e01235",655:"07cb1f6c",728:"ebbeda14",822:"8df94607",866:"d764baec",1011:"728ad61c",1050:"33f429e4",1145:"06e92a4d",1171:"3796c0b9",1235:"f549d2c3",1325:"f9a9e4dd",1378:"6bd42e59",1426:"b2a3e78b",1464:"7eff63e9",1475:"2bc6580d",1492:"c26d5bb6",1494:"eafc393a",1504:"972c6306",1547:"4b0ee92c",1644:"e1df3952",1648:"56c72f30",1763:"dd6ac9f1",1772:"e7125761",1851:"73a3a140",1885:"f2e0ffd7",1960:"e9396e0a",2125:"18eb9afc",2177:"0020fbfc",2183:"695e6dce",2210:"2c53d1aa",2264:"ea10811e",2433:"68cedca8",2445:"369aa5a6",2482:"c1ec5d72",2545:"5685ebf2",2606:"0462ec4c",2661:"adb036a5",2693:"86767de9",2696:"9c4ce6ae",2700:"eb54ab23",2741:"1f389aac",2997:"e8838bb3",3039:"29a37caf",3076:"0d102429",3086:"ce80265a",3089:"305accbe",3184:"0dc3275f",3220:"5fa3179c",3276:"5d0620d6",3343:"c68ed9e0",3388:"5fa079ce",3519:"bd86e6e4",3561:"f1e9070e",3608:"c1ded62d",3618:"7749d78c",3619:"169a66d1",3707:"0d18355b",3713:"0fda5cee",3731:"0a5fb140",3734:"d7742152",3751:"9d2dcf9d",3803:"b36337bc",3887:"6eeb49bf",3979:"928c2eb4",4013:"9b387ded",4064:"3578ba3c",4195:"b182cb1f",4238:"732f7e6d",4256:"b0cfb80e",4269:"143f3da4",4327:"40303d4d",4343:"2970a5ee",4368:"efd630be",4382:"e91bee7a",4394:"60fbe3b9",4562:"cfe53f32",4637:"fd298b3d",4638:"a6f753b6",4706:"bf286a6c",5169:"0ed0fe01",5269:"a9818fb6",5287:"410760a1",5326:"480380dd",5376:"3c894b1e",5430:"839d7f40",5521:"7613dea7",5634:"6ef41b13",5658:"37a3aa6c",5701:"481c535c",5775:"4d6706b7",5790:"a9566ed9",5824:"b21945df",5934:"750e8d79",5943:"ebdacf10",5975:"ba1a6e92",6064:"fd0f7c12",6097:"5b91d377",6103:"78004ce5",6179:"6f772ce2",6255:"4bb462ce",6292:"da5efa5d",6306:"072f92b8",6327:"b6ca83b5",6342:"5cec8345",6435:"b8c94f5a",6519:"974fe1a5",6544:"c79b079a",6573:"aa8d7117",6648:"7d3c04e0",6864:"22b3e630",6890:"92356088",6945:"1665fd21",6985:"b22ddd47",7084:"57b8321c",7257:"e4465696",7292:"6ae62548",7438:"e3b79fad",7568:"a18c3650",7728:"6cbfa670",7743:"4f109cb4",7755:"6fad72ba",7918:"2ef23eb3",7920:"3807d38b",7926:"bfa0084e",7936:"da5208cb",8016:"f7e4e334",8058:"d9b4c84f",8091:"925fdbba",8236:"e64b02a7",8289:"ab09cb54",8326:"58ddb6d9",8387:"dcc463b2",8472:"c32d56e5",8480:"408315a3",8518:"69e4c2b5",8520:"ea246a7d",8529:"33171995",8610:"5be02386",8643:"a09aa523",8757:"1856d5b6",8786:"6458a62f",8807:"9d966504",8894:"bbb1746a",8908:"924b0302",8955:"88257d8a",9066:"e6f69b2d",9138:"e5753066",9173:"986e22d4",9179:"8dd00486",9197:"90e65bfc",9228:"fc107ca5",9249:"312c2807",9300:"bdf83d64",9385:"b012cd5f",9414:"becd0640",9579:"e4b1c753",9661:"8ef24486",9679:"7ab0cc2a",9731:"acb5879a",9771:"162e2ecd",9817:"1936981e",9893:"04fdeb2a",9898:"568886e5",9924:"a5b6acbb"}[e]+".js",t.miniCssF=e=>{},t.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),t.o=(e,a)=>Object.prototype.hasOwnProperty.call(e,a),f={},t.l=(e,a,c,d)=>{if(f[e])f[e].push(a);else{var b,r;if(void 0!==c)for(var o=document.getElementsByTagName("script"),n=0;n{b.onerror=b.onload=null,clearTimeout(l);var d=f[e];if(delete f[e],b.parentNode&&b.parentNode.removeChild(b),d&&d.forEach((e=>e(c))),a)return a(c)},l=setTimeout(u.bind(null,void 0,{type:"timeout",target:b}),12e4);b.onerror=u.bind(null,b.onerror),b.onload=u.bind(null,b.onload),r&&document.head.appendChild(b)}},t.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.p="/",t.gca=function(e){return e={15966941:"8326",17896441:"7918",29694455:"3388",30814625:"115",51624505:"4394",b1288602:"59",dff2ebad:"146","2ca64e35":"281",bc0c9d90:"354","1a606400":"494",ddc7679f:"569",c4c4056e:"635","9a3dc578":"655","686a7a89":"728","8c0e532b":"822","4200b1a9":"866","377f3aa1":"1011",a7098721:"1050","947341b7":"1145",d7f7fb17:"1171","86cd1460":"1235","0220f5fc":"1378","97a42631":"1464",e1d2ae23:"1475",d4b1e057:"1492","16cbc838":"1494","1cd58e77":"1547","48b268a6":"1648","0fcbc6ca":"1851","84d1e0d8":"1885",e31003e9:"1960","06c4a8fc":"2125","3da4b779":"2177","9df0e937":"2210","962da50c":"2264",b5a32f14:"2433",decbf9d1:"2445",dd841e73:"2482","9b91a88c":"2545","08dfa3a2":"2606",d675395f:"2741",d8f4410e:"2997","765ea78b":"3039",cfa2b263:"3086",a6aa9e1f:"3089","7e6d325b":"3184","34ab65f4":"3220","6e3cbca1":"3276","4621632b":"3519","95b96bb9":"3561","9e4087bc":"3608",a6a48ea2:"3618","24fecc0a":"3707","698e2076":"3713","087808f1":"3731","0123bc76":"3734","3720c009":"3751","794ef108":"3803","933b95b3":"3887","2af5d0a7":"3979","01a85c17":"4013",f48be158:"4064",c4f5d8e4:"4195","75cccf44":"4256","0bfe45d5":"4269","4e546705":"4327",df0885f0:"4343",a94703ab:"4368",a4c10cf4:"4382","976c4f3b":"4562","19d7c045":"4637","2fcf0558":"4638",d79dd549:"5169","6bc697d0":"5287","1535ede8":"5376","52f2a5bf":"5430","9287eafd":"5521","595c7293":"5634",af8b72a7:"5658","3adcbc3a":"5701","8e6bb954":"5775",a80747a0:"5824",f75910c4:"5934","4edd2021":"5975","7ce7faac":"6064",b0291f37:"6097",ccc49370:"6103",d57b4369:"6179",d255bd7f:"6292","4f96b16e":"6306",fb4361d3:"6327","2b89902a":"6342","28d80ff8":"6435",bc2d22bc:"6519",d05e838c:"6544",c580b66a:"6573",bb984793:"6864","22a175ec":"6890","45c9e308":"7084",aa24fd5d:"7257","493c0536":"7292",b8cbf382:"7438","0608d96f":"7568","8a25f659":"7728",df078f58:"7743",ab2721d4:"7755","1a4e3797":"7920","3011a4c0":"7926","520f8175":"8058",bb882650:"8091","3d92ba6e":"8236",a2ba8888:"8289",eba2374c:"8387",ff82dde7:"8472","8b1802c5":"8480",a7bd4aaa:"8518","62d847b3":"8520","1acf65cc":"8529","6875c492":"8610",ff472cd9:"8643",e89da83e:"8757",a082abd3:"8786",dead8108:"8807",d309b5b1:"8908","8d31a880":"9066","5ca803d2":"9173",b9f7f5c4:"9179",b25fbc58:"9197","66d5ef6c":"9228","70a4540f":"9249","146d9b84":"9300","95f41f0b":"9385","354a7b72":"9414","5c15401e":"9579","5e95c892":"9661",b45dccf0:"9679","7052c0bc":"9731","534d4833":"9771","14eb3368":"9817","0178f9ad":"9898",df203c0f:"9924"}[e]||e,t.p+t.u(e)},(()=>{var e={1303:0,532:0};t.f.j=(a,c)=>{var f=t.o(e,a)?e[a]:void 0;if(0!==f)if(f)c.push(f[2]);else if(/^(1303|532)$/.test(a))e[a]=0;else{var d=new Promise(((c,d)=>f=e[a]=[c,d]));c.push(f[2]=d);var b=t.p+t.u(a),r=new Error;t.l(b,(c=>{if(t.o(e,a)&&(0!==(f=e[a])&&(e[a]=void 0),f)){var d=c&&("load"===c.type?"missing":c.type),b=c&&c.target&&c.target.src;r.message="Loading chunk "+a+" failed.\n("+d+": "+b+")",r.name="ChunkLoadError",r.type=d,r.request=b,f[1](r)}}),"chunk-"+a,a)}},t.O.j=a=>0===e[a];var a=(a,c)=>{var f,d,b=c[0],r=c[1],o=c[2],n=0;if(b.some((a=>0!==e[a]))){for(f in r)t.o(r,f)&&(t.m[f]=r[f]);if(o)var i=o(t)}for(a&&a(c);n - + diff --git a/blog/aoc-2022/1st-week/index.html b/blog/aoc-2022/1st-week/index.html index 9678549..4655e3e 100644 --- a/blog/aoc-2022/1st-week/index.html +++ b/blog/aoc-2022/1st-week/index.html @@ -14,7 +14,7 @@ - + @@ -118,7 +118,7 @@ Find how many overlap and can take the day off.

Day 5: Supply Stacks

tl;dr

Let's play with stacks of crates.

Very easy problem with very annoying input. You can judge yourself:

-
    [D]    
[N] [C]
[Z] [M] [P]
1 2 3

move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2
+
    [D]
[N] [C]
[Z] [M] [P]
1 2 3

move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2

Good luck transforming that into something reasonable :)

Fun fact

Took me 40 minutes to parse this reasonably, including fighting the compiler.

Solution

diff --git a/blog/aoc-2022/2nd-week/index.html b/blog/aoc-2022/2nd-week/index.html index 95ac7d0..a870488 100644 --- a/blog/aoc-2022/2nd-week/index.html +++ b/blog/aoc-2022/2nd-week/index.html @@ -14,7 +14,7 @@ - + @@ -302,7 +302,7 @@ right? Yes… but actually no 😦

the fun part consists of the fact that in other place, where we were using it, we were passing the &[Vec<T>], but this is coming from a helper functions that take &Vec<Vec<T>> instead. And… we don't implement Index and IndexMut for -those. Just for the slices. 🤯 What are we going to do about it?

+those. Just for the slices. 🤯 What are we going to do about it?

We can either start copy-pasting or be smarter about it… I choose to be smarter, so let's implement a macro! The only difference across the implementations are the types of the outer containers. Implementation doesn't differ at all!

diff --git a/blog/aoc-2022/3rd-week/index.html b/blog/aoc-2022/3rd-week/index.html index dda6385..05fee4d 100644 --- a/blog/aoc-2022/3rd-week/index.html +++ b/blog/aoc-2022/3rd-week/index.html @@ -14,7 +14,7 @@ - + diff --git a/blog/aoc-2022/4th-week/index.html b/blog/aoc-2022/4th-week/index.html index a01ec5a..768fa82 100644 --- a/blog/aoc-2022/4th-week/index.html +++ b/blog/aoc-2022/4th-week/index.html @@ -14,7 +14,7 @@ - + @@ -230,7 +230,7 @@ everything:

You can also see that it simplifies the meaning a bit and it is more explicit than the previous versions.

And for the tests:

-
     #[test]
fn test_from() {
- for (n, s) in EXAMPLES.iter() {
- assert_eq!(from_snafu(s), *n);
+ for (&n, s) in EXAMPLES.iter() {
+ assert_eq!(s.parse::<SNAFU>().unwrap().value, n);
}
}

#[test]
fn test_to() {
- for (n, s) in EXAMPLES.iter() {
- assert_eq!(to_snafu(*n), s.to_string());
+ for (&n, s) in EXAMPLES.iter() {
+ assert_eq!(SNAFU::from(n).to_string(), s.to_string());
}
+
     #[test]
fn test_from() {
- for (n, s) in EXAMPLES.iter() {
- assert_eq!(from_snafu(s), *n);
+ for (&n, s) in EXAMPLES.iter() {
+ assert_eq!(s.parse::<SNAFU>().unwrap().value, n);
}
}

#[test]
fn test_to() {
- for (n, s) in EXAMPLES.iter() {
- assert_eq!(to_snafu(*n), s.to_string());
+ for (&n, s) in EXAMPLES.iter() {
+ assert_eq!(SNAFU::from(n).to_string(), s.to_string());
}

Summary

Let's wrap the whole thing up! Keeping in mind both AoC and the Rust…

Finished advent calendar :smile:

diff --git a/blog/aoc-2022/intro/index.html b/blog/aoc-2022/intro/index.html index 4b1a685..4e49fd2 100644 --- a/blog/aoc-2022/intro/index.html +++ b/blog/aoc-2022/intro/index.html @@ -14,7 +14,7 @@ - + diff --git a/blog/archive/index.html b/blog/archive/index.html index d7eaeb9..64345a7 100644 --- a/blog/archive/index.html +++ b/blog/archive/index.html @@ -14,7 +14,7 @@ - + diff --git a/blog/atom.xml b/blog/atom.xml index 3c265e6..448644b 100644 --- a/blog/atom.xml +++ b/blog/atom.xml @@ -317,7 +317,7 @@ everything:

You can also see that it simplifies the meaning a bit and it is more explicit than the previous versions.

And for the tests:

-
     #[test]
fn test_from() {
- for (n, s) in EXAMPLES.iter() {
- assert_eq!(from_snafu(s), *n);
+ for (&n, s) in EXAMPLES.iter() {
+ assert_eq!(s.parse::<SNAFU>().unwrap().value, n);
}
}

#[test]
fn test_to() {
- for (n, s) in EXAMPLES.iter() {
- assert_eq!(to_snafu(*n), s.to_string());
+ for (&n, s) in EXAMPLES.iter() {
+ assert_eq!(SNAFU::from(n).to_string(), s.to_string());
}
+
     #[test]
fn test_from() {
- for (n, s) in EXAMPLES.iter() {
- assert_eq!(from_snafu(s), *n);
+ for (&n, s) in EXAMPLES.iter() {
+ assert_eq!(s.parse::<SNAFU>().unwrap().value, n);
}
}

#[test]
fn test_to() {
- for (n, s) in EXAMPLES.iter() {
- assert_eq!(to_snafu(*n), s.to_string());
+ for (&n, s) in EXAMPLES.iter() {
+ assert_eq!(SNAFU::from(n).to_string(), s.to_string());
}

Summary

Let's wrap the whole thing up! Keeping in mind both AoC and the Rust…

Finished advent calendar :smile:

@@ -591,7 +591,7 @@ order and return the resulting matrix.

Image describing the problem

Skeleton and initial adjustments

We are given the following skeleton for the C++ and the given challenge:

-
class Solution {
public:
vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {

}
};
+
class Solution {
public:
vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {

}
};

The task is to sort the passed matrix diagonally and then return it. First of all, I don't like to solve this in a web browser, so we'll need to adjust it accordingly for running it locally. We'll start by including the vector header and using @@ -1078,7 +1078,7 @@ right? Yes… but actually no 😦

the fun part consists of the fact that in other place, where we were using it, we were passing the &[Vec<T>], but this is coming from a helper functions that take &Vec<Vec<T>> instead. And… we don't implement Index and IndexMut for -those. Just for the slices. 🤯 What are we going to do about it?

+those. Just for the slices. 🤯 What are we going to do about it?

We can either start copy-pasting or be smarter about it… I choose to be smarter, so let's implement a macro! The only difference across the implementations are the types of the outer containers. Implementation doesn't differ at all!

@@ -1217,7 +1217,7 @@ Find how many overlap and can take the day off.

Day 5: Supply Stacks

tl;dr

Let's play with stacks of crates.

Very easy problem with very annoying input. You can judge yourself:

-
    [D]    
[N] [C]
[Z] [M] [P]
1 2 3

move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2
+
    [D]
[N] [C]
[Z] [M] [P]
1 2 3

move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2

Good luck transforming that into something reasonable :)

Fun fact

Took me 40 minutes to parse this reasonably, including fighting the compiler.

Solution

diff --git a/blog/feed.json b/blog/feed.json index 34380cc..22db6f5 100644 --- a/blog/feed.json +++ b/blog/feed.json @@ -25,7 +25,7 @@ }, { "id": "https://blog.mfocko.xyz/blog/aoc-2022/4th-week", - "content_html": "

Let's go through the fourth week of Advent of Code in Rust.

\n

Day 22: Monkey Map

\n
tl;dr

Simulating a movement on a 2D map with given instructions. Map becomes a cube in\nthe 2nd part…

\n
Rant

This was the most obnoxious problem of this year… and a lot of Rust issues have\nbeen hit.

\n

Solution

\n

It 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 »properly«.

\n

Column iterator

\n

In 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 “array”. 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

For this use case I have implemented my own column iterator:

\n
pub struct ColumnIterator<'a, T> {
map: &'a [Vec<T>],
column: usize,

i: usize,
}

impl<'a, T> ColumnIterator<'a, T> {
pub fn new(map: &'a [Vec<T>], column: usize) -> ColumnIterator<'a, T> {
Self { map, column, i: 0 }
}
}

impl<'a, T> Iterator for ColumnIterator<'a, T> {
type Item = &'a T;

fn next(&mut self) -> Option<Self::Item> {
if self.i >= self.map.len() {
return None;
}

self.i += 1;
Some(&self.map[self.i - 1][self.column])
}
}
\n

Given this piece of an iterator, it is very easy to factor out the common\nfunctionality between the rows and columns into:

\n
let mut find_boundaries = |constructor: fn(usize) -> Orientation,
iterator: &mut dyn Iterator<Item = &char>,
upper_bound,
i| {
let mut first_non_empty = iterator.enumerate().skip_while(|&(_, &c)| c == ' ');
let start = first_non_empty.next().unwrap().0 as isize;

let mut last_non_empty = first_non_empty.skip_while(|&(_, &c)| c != ' ');
let end = last_non_empty.next().unwrap_or((upper_bound, &'_')).0 as isize;

boundaries.insert(constructor(i), start..end);
};
\n

And then use it as such:

\n
// construct all horizontal boundaries
(0..map.len()).for_each(|row| {
find_boundaries(
Orientation::horizontal,
&mut map[row].iter(),
map[row].len(),
row,
);
});

// construct all vertical boundaries
(0..map[0].len()).for_each(|col| {
find_boundaries(
Orientation::vertical,
&mut ColumnIterator::new(&map, col),
map.len(),
col,
);
});
\n

Walking around the map

\n

Once 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…). In this problem, I've\nchosen to introduce a trait (i.e. interface) for 2D and 3D walker.

\n
trait Wrap: Clone {
type State;

// simulation
fn is_blocked(&self) -> bool;
fn step(&mut self, steps: isize);
fn turn_left(&mut self);
fn turn_right(&mut self);

// movement
fn next(&self) -> (Self::State, Direction);

// final answer
fn answer(&self) -> Output;
}
\n

Each walker maintains its own state and also provides the functions that are\nused during the simulation. The “promised” methods are separated into:

\n
    \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\nbetween 2D and 3D
  • \n
  • final answer: which extracts the proof of solution from the\nimplementation-specific walker
  • \n
\n

Both 2D and 3D versions borrow the original input and therefore you must\nannotate the lifetime of it:

\n
struct Wrap2D<'a> {
input: &'a Input,
position: Position,
direction: Direction,
}
impl<'a> Wrap2D<'a> {
fn new(input: &'a Input) -> Wrap2D<'a> {
// …
\n

Problems

\n

I 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 “fix” for the compilation error that resulted in something that\nwas not possible to parse, cause it, more than likely, violated the grammar.

\n

In 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. 😄

\n

Clippy

\n

I have to admit that Clippy was rather helpful here, I'll include two examples\nof rather smart suggestions.

\n

When writing the parsing for this problem, the first thing I have spotted on the\nchar 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
-                .take_while(|c| c.is_digit(10))
+ .take_while(|c| c.is_ascii_digit())
\n

Another useful suggestion appeared when working with the iterators and I wanted\nto get the nnn-th element from it. You know the .skip(), you know the\n.next(), just “slap” them together and we're done for 😁 Well, I got\nsuggested to use .nth() that does exactly the combination of the two mentioned\nmethods on iterators:

\n
-            match it.clone().skip(skip).next().unwrap() {
+ match it.clone().nth(skip).unwrap() {
\n

Day 23: Unstable Diffusion

\n
tl;dr

Simulating movement of elves around with a set of specific rules.

\n

Solution

\n

There'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😉).

\n

Although 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
fn get_bounds(positions: &Input) -> (Vector2D<isize>, Vector2D<isize>) {
let f = |init, cmp: &dyn Fn(isize, isize) -> isize| {
positions
.iter()
.fold(Vector2D::new(init, init), |acc, elf| {
Vector2D::new(cmp(acc.x(), elf.x()), cmp(acc.y(), elf.y()))
})
};

(f(isize::MAX, &min::<isize>), f(isize::MIN, &max::<isize>))
}
\n

This function returns a pair of 2D vectors that represent opposite points of the\nbounding rectangle of all elves.

\n

You 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
&dyn Fn(isize, isize) -> isize
\n

Once 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

$ rustc --explain E0782

\n

which shows us

\n

Trait objects must include the dyn keyword.

\n

Erroneous code example:

\n
trait Foo {}
fn test(arg: Box<Foo>) {} // error!
\n

Trait objects are a way to call methods on types that are not known until\nruntime but conform to some trait.

\n

Trait objects should be formed with Box<dyn Foo>, but in the code above\ndyn is left off.

\n

This makes it harder to see that arg is a trait object and not a\nsimply a heap allocated type called Foo.

\n

To fix this issue, add dyn before the trait name.

\n
trait Foo {}
fn test(arg: Box<dyn Foo>) {} // ok!
\n

This used to be allowed before edition 2021, but is now an error.

\n
Rant

Not 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.

As 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>\nthat, as you can see in my snippet, does not apply here 😄 IMO it's\ncaused by the fact that we are borrowing it and therefore we don't need to\ncare about the size or whereabouts of it.
  • \n
\n
C++ parallel

If 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).

On 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

Day 24: Blizzard Basin

\n
tl;dr

Navigating your way through a basin with series of blizzards that move around\nyou as you move.

\n
caution

It's second to last day and I went “bonkers” on the Rust 😄 Proceed to\nread Solution part on your own risk.

\n

Solution

\n

You 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

Breakdown

\n

Relatively 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? 😉

\n

Evaluating the blizzards

\n
caution

I think that this is the most perverted abuse of the traits in the whole 4 weeks\nof AoC in Rust…

\n

The 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\njust index the basin with the vertex itself, right? Yes, we can 😈

\n
Fun fact

While 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

I'll skip the boring parts of checking bounds and entry/exit of the basin 😉\nWe can easily calculate positions of the blizzards using a modular arithmetics:

\n
impl Index<Position> for Basin {
type Output = char;

fn index(&self, index: Position) -> &Self::Output {
// ‹skipped boring parts›

// We need to account for the loops of the blizzards
let width = self.cols - 2;
let height = self.rows - 2;

let blizzard_origin = |size, d, t, i| ((i - 1 + size + d * (t % size)) % size + 1) as usize;
[
(
index.y() as usize,
blizzard_origin(width, -1, index.z(), index.x()),
'>',
),
(
index.y() as usize,
blizzard_origin(width, 1, index.z(), index.x()),
'<',
),
(
blizzard_origin(height, -1, index.z(), index.y()),
index.x() as usize,
'v',
),
(
blizzard_origin(height, 1, index.z(), index.y()),
index.x() as usize,
'^',
),
]
.iter()
.find_map(|&(y, x, direction)| {
if self.map[y][x] == direction {
Some(&self.map[y][x])
} else {
None
}
})
.unwrap_or(&'.')
}
}
\n

As 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? 😉

\n

I 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

I think it's a very nice (and naughty) way how to use the Index trait, don't\nyou think?

\n

Shortest-path algorithm

\n

For 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
Comparison of costs

With the Dijkstra's algorithm I would proceed with the time attribute used as\na priority for the queue.

Whereas 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

Cost function is, of course, a closure 😉

\n
let cost = |p: Position| p.z() as usize + exit.y().abs_diff(p.y()) + exit.x().abs_diff(p.x());
\n

And 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
let next_positions = |p| {
[(0, 0, 1), (0, -1, 1), (0, 1, 1), (-1, 0, 1), (1, 0, 1)]
.iter()
.filter_map(move |&(x, y, t)| {
let next_p = p + Vector3D::new(x, y, t);

if basin[next_p] == '.' {
Some(next_p)
} else {
None
}
})
};
\n

Min-heap

\n

In 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

For 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
use std::cmp::{Ord, Reverse};
use std::collections::BinaryHeap;

pub struct MinHeap<T> {
heap: BinaryHeap<Reverse<T>>,
}

impl<T: Ord> MinHeap<T> {
pub fn new() -> MinHeap<T> {
MinHeap {
heap: BinaryHeap::new(),
}
}

pub fn push(&mut self, item: T) {
self.heap.push(Reverse(item))
}

pub fn pop(&mut self) -> Option<T> {
self.heap.pop().map(|Reverse(x)| x)
}
}

impl<T: Ord> Default for MinHeap<T> {
fn default() -> Self {
Self::new()
}
}
\n

Rest is just the algorithm implementation which is not that interesting.

\n

Day 25: Full of Hot Air

\n
tl;dr

Playing around with a numbers in a special base.

\n

Getting flashbacks to the IB111 Foundations of Programming… Very nice “problem”\nwith a rather easy solution, as the last day always seems to be.

\n

Solution

\n

Implementing 2 functions, converting from the SNAFU base and back to the SNAFU\nbase representation. Let's do a bit more though! I have implemented two functions:

\n
    \n
  • from_snafu
  • \n
  • to_snafu
  • \n
\n

Now it is apparent that all I do is number to string and string to number. Hmm…\nthat sounds familiar, doesn't it? Let's introduce a structure for the SNAFU numbers\nand implement the traits that we need.

\n

Let's start with a structure:

\n
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct SNAFU {
value: i64,
}
\n

Converting from &str

\n

We 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\nSNAFU structure.

\n

Converting to String

\n

This 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

Let'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

And for the convenience of tests, we can also implement a rather simple From<i64>\ntrait for the SNAFU.

\n

Adjusting the code

\n

After those changes we need to adjust the code and tests.

\n

Parsing of the input is very easy, before we have used the lines, now we parse\neverything:

\n
     fn parse_input<P: AsRef<Path>>(pathname: P) -> Input {
- file_to_lines(pathname)
+ file_to_structs(pathname)
}
\n

Part 1 needs to be adjusted a bit too:

\n
     fn part_1(input: &Input) -> Output {
- to_snafu(input.iter().map(|s| from_snafu(s)).sum())
+ SNAFU::from(input.iter().map(|s| s.value).sum::<i64>()).to_string()
}
\n

You can also see that it simplifies the meaning a bit and it is more explicit than\nthe previous versions.

\n

And for the tests:

\n
     #[test]
fn test_from() {
- for (n, s) in EXAMPLES.iter() {
- assert_eq!(from_snafu(s), *n);
+ for (&n, s) in EXAMPLES.iter() {
+ assert_eq!(s.parse::<SNAFU>().unwrap().value, n);
}
}

#[test]
fn test_to() {
- for (n, s) in EXAMPLES.iter() {
- assert_eq!(to_snafu(*n), s.to_string());
+ for (&n, s) in EXAMPLES.iter() {
+ assert_eq!(SNAFU::from(n).to_string(), s.to_string());
}
\n

Summary

\n

Let's wrap the whole thing up! Keeping in mind both AoC and the Rust…

\n

\"Finished

\n

Advent of Code

\n

This 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… And also\nit feels like I used priority queues and tree data structures a lot 👀

\n

with Rust

\n

I 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

Building my first tree data structure in Rust has been a very “interesting”\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

I am definitely much more aware of the basic things that bloated Python is\nmissing, yet Rust has them…

\n

Using 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

I 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

I confess to touching more “cursed” 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

tl;dr Relatively pleasant language until you hit brick wall 😉

\n
\n

See you next year! Maybe in Rust, maybe not 🙃

", + "content_html": "

Let's go through the fourth week of Advent of Code in Rust.

\n

Day 22: Monkey Map

\n
tl;dr

Simulating a movement on a 2D map with given instructions. Map becomes a cube in\nthe 2nd part…

\n
Rant

This was the most obnoxious problem of this year… and a lot of Rust issues have\nbeen hit.

\n

Solution

\n

It 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 »properly«.

\n

Column iterator

\n

In 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 “array”. 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

For this use case I have implemented my own column iterator:

\n
pub struct ColumnIterator<'a, T> {
map: &'a [Vec<T>],
column: usize,

i: usize,
}

impl<'a, T> ColumnIterator<'a, T> {
pub fn new(map: &'a [Vec<T>], column: usize) -> ColumnIterator<'a, T> {
Self { map, column, i: 0 }
}
}

impl<'a, T> Iterator for ColumnIterator<'a, T> {
type Item = &'a T;

fn next(&mut self) -> Option<Self::Item> {
if self.i >= self.map.len() {
return None;
}

self.i += 1;
Some(&self.map[self.i - 1][self.column])
}
}
\n

Given this piece of an iterator, it is very easy to factor out the common\nfunctionality between the rows and columns into:

\n
let mut find_boundaries = |constructor: fn(usize) -> Orientation,
iterator: &mut dyn Iterator<Item = &char>,
upper_bound,
i| {
let mut first_non_empty = iterator.enumerate().skip_while(|&(_, &c)| c == ' ');
let start = first_non_empty.next().unwrap().0 as isize;

let mut last_non_empty = first_non_empty.skip_while(|&(_, &c)| c != ' ');
let end = last_non_empty.next().unwrap_or((upper_bound, &'_')).0 as isize;

boundaries.insert(constructor(i), start..end);
};
\n

And then use it as such:

\n
// construct all horizontal boundaries
(0..map.len()).for_each(|row| {
find_boundaries(
Orientation::horizontal,
&mut map[row].iter(),
map[row].len(),
row,
);
});

// construct all vertical boundaries
(0..map[0].len()).for_each(|col| {
find_boundaries(
Orientation::vertical,
&mut ColumnIterator::new(&map, col),
map.len(),
col,
);
});
\n

Walking around the map

\n

Once 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…). In this problem, I've\nchosen to introduce a trait (i.e. interface) for 2D and 3D walker.

\n
trait Wrap: Clone {
type State;

// simulation
fn is_blocked(&self) -> bool;
fn step(&mut self, steps: isize);
fn turn_left(&mut self);
fn turn_right(&mut self);

// movement
fn next(&self) -> (Self::State, Direction);

// final answer
fn answer(&self) -> Output;
}
\n

Each walker maintains its own state and also provides the functions that are\nused during the simulation. The “promised” methods are separated into:

\n
    \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\nbetween 2D and 3D
  • \n
  • final answer: which extracts the proof of solution from the\nimplementation-specific walker
  • \n
\n

Both 2D and 3D versions borrow the original input and therefore you must\nannotate the lifetime of it:

\n
struct Wrap2D<'a> {
input: &'a Input,
position: Position,
direction: Direction,
}
impl<'a> Wrap2D<'a> {
fn new(input: &'a Input) -> Wrap2D<'a> {
// …
\n

Problems

\n

I 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 “fix” for the compilation error that resulted in something that\nwas not possible to parse, cause it, more than likely, violated the grammar.

\n

In 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. 😄

\n

Clippy

\n

I have to admit that Clippy was rather helpful here, I'll include two examples\nof rather smart suggestions.

\n

When writing the parsing for this problem, the first thing I have spotted on the\nchar 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
-                .take_while(|c| c.is_digit(10))
+ .take_while(|c| c.is_ascii_digit())
\n

Another useful suggestion appeared when working with the iterators and I wanted\nto get the nnn-th element from it. You know the .skip(), you know the\n.next(), just “slap” them together and we're done for 😁 Well, I got\nsuggested to use .nth() that does exactly the combination of the two mentioned\nmethods on iterators:

\n
-            match it.clone().skip(skip).next().unwrap() {
+ match it.clone().nth(skip).unwrap() {
\n

Day 23: Unstable Diffusion

\n
tl;dr

Simulating movement of elves around with a set of specific rules.

\n

Solution

\n

There'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😉).

\n

Although 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
fn get_bounds(positions: &Input) -> (Vector2D<isize>, Vector2D<isize>) {
let f = |init, cmp: &dyn Fn(isize, isize) -> isize| {
positions
.iter()
.fold(Vector2D::new(init, init), |acc, elf| {
Vector2D::new(cmp(acc.x(), elf.x()), cmp(acc.y(), elf.y()))
})
};

(f(isize::MAX, &min::<isize>), f(isize::MIN, &max::<isize>))
}
\n

This function returns a pair of 2D vectors that represent opposite points of the\nbounding rectangle of all elves.

\n

You 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
&dyn Fn(isize, isize) -> isize
\n

Once 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

$ rustc --explain E0782

\n

which shows us

\n

Trait objects must include the dyn keyword.

\n

Erroneous code example:

\n
trait Foo {}
fn test(arg: Box<Foo>) {} // error!
\n

Trait objects are a way to call methods on types that are not known until\nruntime but conform to some trait.

\n

Trait objects should be formed with Box<dyn Foo>, but in the code above\ndyn is left off.

\n

This makes it harder to see that arg is a trait object and not a\nsimply a heap allocated type called Foo.

\n

To fix this issue, add dyn before the trait name.

\n
trait Foo {}
fn test(arg: Box<dyn Foo>) {} // ok!
\n

This used to be allowed before edition 2021, but is now an error.

\n
Rant

Not 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.

As 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>\nthat, as you can see in my snippet, does not apply here 😄 IMO it's\ncaused by the fact that we are borrowing it and therefore we don't need to\ncare about the size or whereabouts of it.
  • \n
\n
C++ parallel

If 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).

On 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

Day 24: Blizzard Basin

\n
tl;dr

Navigating your way through a basin with series of blizzards that move around\nyou as you move.

\n
caution

It's second to last day and I went “bonkers” on the Rust 😄 Proceed to\nread Solution part on your own risk.

\n

Solution

\n

You 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

Breakdown

\n

Relatively 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? 😉

\n

Evaluating the blizzards

\n
caution

I think that this is the most perverted abuse of the traits in the whole 4 weeks\nof AoC in Rust…

\n

The 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\njust index the basin with the vertex itself, right? Yes, we can 😈

\n
Fun fact

While 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

I'll skip the boring parts of checking bounds and entry/exit of the basin 😉\nWe can easily calculate positions of the blizzards using a modular arithmetics:

\n
impl Index<Position> for Basin {
type Output = char;

fn index(&self, index: Position) -> &Self::Output {
// ‹skipped boring parts›

// We need to account for the loops of the blizzards
let width = self.cols - 2;
let height = self.rows - 2;

let blizzard_origin = |size, d, t, i| ((i - 1 + size + d * (t % size)) % size + 1) as usize;
[
(
index.y() as usize,
blizzard_origin(width, -1, index.z(), index.x()),
'>',
),
(
index.y() as usize,
blizzard_origin(width, 1, index.z(), index.x()),
'<',
),
(
blizzard_origin(height, -1, index.z(), index.y()),
index.x() as usize,
'v',
),
(
blizzard_origin(height, 1, index.z(), index.y()),
index.x() as usize,
'^',
),
]
.iter()
.find_map(|&(y, x, direction)| {
if self.map[y][x] == direction {
Some(&self.map[y][x])
} else {
None
}
})
.unwrap_or(&'.')
}
}
\n

As 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? 😉

\n

I 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

I think it's a very nice (and naughty) way how to use the Index trait, don't\nyou think?

\n

Shortest-path algorithm

\n

For 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
Comparison of costs

With the Dijkstra's algorithm I would proceed with the time attribute used as\na priority for the queue.

Whereas 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

Cost function is, of course, a closure 😉

\n
let cost = |p: Position| p.z() as usize + exit.y().abs_diff(p.y()) + exit.x().abs_diff(p.x());
\n

And 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
let next_positions = |p| {
[(0, 0, 1), (0, -1, 1), (0, 1, 1), (-1, 0, 1), (1, 0, 1)]
.iter()
.filter_map(move |&(x, y, t)| {
let next_p = p + Vector3D::new(x, y, t);

if basin[next_p] == '.' {
Some(next_p)
} else {
None
}
})
};
\n

Min-heap

\n

In 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

For 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
use std::cmp::{Ord, Reverse};
use std::collections::BinaryHeap;

pub struct MinHeap<T> {
heap: BinaryHeap<Reverse<T>>,
}

impl<T: Ord> MinHeap<T> {
pub fn new() -> MinHeap<T> {
MinHeap {
heap: BinaryHeap::new(),
}
}

pub fn push(&mut self, item: T) {
self.heap.push(Reverse(item))
}

pub fn pop(&mut self) -> Option<T> {
self.heap.pop().map(|Reverse(x)| x)
}
}

impl<T: Ord> Default for MinHeap<T> {
fn default() -> Self {
Self::new()
}
}
\n

Rest is just the algorithm implementation which is not that interesting.

\n

Day 25: Full of Hot Air

\n
tl;dr

Playing around with a numbers in a special base.

\n

Getting flashbacks to the IB111 Foundations of Programming… Very nice “problem”\nwith a rather easy solution, as the last day always seems to be.

\n

Solution

\n

Implementing 2 functions, converting from the SNAFU base and back to the SNAFU\nbase representation. Let's do a bit more though! I have implemented two functions:

\n
    \n
  • from_snafu
  • \n
  • to_snafu
  • \n
\n

Now it is apparent that all I do is number to string and string to number. Hmm…\nthat sounds familiar, doesn't it? Let's introduce a structure for the SNAFU numbers\nand implement the traits that we need.

\n

Let's start with a structure:

\n
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct SNAFU {
value: i64,
}
\n

Converting from &str

\n

We 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\nSNAFU structure.

\n

Converting to String

\n

This 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

Let'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

And for the convenience of tests, we can also implement a rather simple From<i64>\ntrait for the SNAFU.

\n

Adjusting the code

\n

After those changes we need to adjust the code and tests.

\n

Parsing of the input is very easy, before we have used the lines, now we parse\neverything:

\n
     fn parse_input<P: AsRef<Path>>(pathname: P) -> Input {
- file_to_lines(pathname)
+ file_to_structs(pathname)
}
\n

Part 1 needs to be adjusted a bit too:

\n
     fn part_1(input: &Input) -> Output {
- to_snafu(input.iter().map(|s| from_snafu(s)).sum())
+ SNAFU::from(input.iter().map(|s| s.value).sum::<i64>()).to_string()
}
\n

You can also see that it simplifies the meaning a bit and it is more explicit than\nthe previous versions.

\n

And for the tests:

\n
     #[test]
fn test_from() {
- for (n, s) in EXAMPLES.iter() {
- assert_eq!(from_snafu(s), *n);
+ for (&n, s) in EXAMPLES.iter() {
+ assert_eq!(s.parse::<SNAFU>().unwrap().value, n);
}
}

#[test]
fn test_to() {
- for (n, s) in EXAMPLES.iter() {
- assert_eq!(to_snafu(*n), s.to_string());
+ for (&n, s) in EXAMPLES.iter() {
+ assert_eq!(SNAFU::from(n).to_string(), s.to_string());
}
\n

Summary

\n

Let's wrap the whole thing up! Keeping in mind both AoC and the Rust…

\n

\"Finished

\n

Advent of Code

\n

This 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… And also\nit feels like I used priority queues and tree data structures a lot 👀

\n

with Rust

\n

I 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

Building my first tree data structure in Rust has been a very “interesting”\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

I am definitely much more aware of the basic things that bloated Python is\nmissing, yet Rust has them…

\n

Using 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

I 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

I confess to touching more “cursed” 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

tl;dr Relatively pleasant language until you hit brick wall 😉

\n
\n

See you next year! Maybe in Rust, maybe not 🙃

", "url": "https://blog.mfocko.xyz/blog/aoc-2022/4th-week", "title": "4th week of Advent of Code '22 in Rust", "summary": "Surviving fourth week in Rust.", @@ -59,7 +59,7 @@ }, { "id": "https://blog.mfocko.xyz/blog/leetcode/sort-diagonally", - "content_html": "

Let's try to solve one of the LeetCode challenges in easy and hard mode at the\nsame time.

\n\n

Problem description

\n

A 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],\nmat[3][1], and mat[4][2].

\n

Given an m x n matrix mat of integers, sort each matrix diagonal in ascending\norder and return the resulting matrix.

\n

Example

\n

\"Image

\n

Skeleton and initial adjustments

\n

We are given the following skeleton for the C++ and the given challenge:

\n
class Solution {
public:
vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {

}
};
\n

The 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 namespaces1 and also adding few tests:

\n
#include <cassert>
#include <vector>

using matrix = std::vector<std::vector<int>>;

class Solution {
public:
matrix diagonalSort(matrix& mat)
{
}
};

static void test_case_1()
{
// Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]
// Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]

Solution s;
assert((s.diagonalSort(std::vector { std::vector { 3, 3, 1, 1 },
std::vector { 2, 2, 1, 2 },
std::vector { 1, 1, 1, 2 } })
== std::vector { std::vector { 1, 1, 1, 1 },
std::vector { 1, 2, 2, 2 },
std::vector { 1, 2, 3, 3 } }));
}

static void test_case_2()
{
// Input: mat =
// [[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]]
// Output:
// [[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]]

Solution s;
assert((s.diagonalSort(std::vector { std::vector { 11, 25, 66, 1, 69, 7 },
std::vector { 23, 55, 17, 45, 15, 52 },
std::vector { 75, 31, 36, 44, 58, 8 },
std::vector { 22, 27, 33, 25, 68, 4 },
std::vector { 84, 28, 14, 11, 5, 50 } })
== std::vector { std::vector { 5, 17, 4, 1, 52, 7 },
std::vector { 11, 11, 25, 45, 8, 69 },
std::vector { 14, 23, 25, 44, 58, 15 },
std::vector { 22, 27, 31, 36, 50, 66 },
std::vector { 84, 28, 75, 33, 55, 68 } }));
}

int main()
{
test_case_1();
test_case_2();

return 0;
}
\n

We 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 “shut up” we will just return\nthe input for now:

\n
-    matrix diagonalSort(matrix& mat)
+ matrix diagonalSort(matrix mat)
{
+ return mat;
}
\n

Now, we get the copy and we're good to go.

\n

Naïve solution

\n

As you may know, C++ offers a plethora of functions that can be used to your\nadvantage, given that you know how to “bend” the data structures accordingly.

\n

What does that mean for us? Well, we have an std::sort, we can use it, right?\nLet's have a look at it:

\n
template< class RandomIt >
void sort( RandomIt first, RandomIt last );
\n

This 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… we can sort just »one« diagonal without doing much work\non our end.

\n

What 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\niterator and allows swapping its values at the same time.

\n
Random access iterator

What is the random access iterator though? We can find it in a documentation\nand see the following description:

\n

A LegacyRandomAccessIterator is a LegacyBidirectionalIterator\nthat can be moved to point to any element in constant time.

\n

After 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. “compiler-assisted development2 if you will ;)

\n

Now 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 else3. And that way we get

\n
matrix diagonalSort(matrix mat)
{
// we iterate over the diagonals
for (auto d : diagonals(mat)) {
// and we sort each diagonal
std::sort(d.begin(), d.end());
}

// we take the matrix by copy, so we can sort in-situ and return the copy
// that we sorted
return mat;
}
\n

This solution looks very simple, doesn't it? Well, cause it is.\nLet's try compiling it:

\n
matrix-sort.cpp:11:23: error: use of undeclared identifier 'diagonals' [clang-diagnostic-error]
for (auto d : diagonals(mat)) {
^
Found compiler error(s).
make: *** [makefile:14: tidy] Error 1
\n

OK, 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

Implementing the diagonals

\n

Cool, 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\ndiagonals 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

As I said, we need to be able to

\n
    \n
  • construct the object
  • \n
  • get the beginning
  • \n
  • get the end (the “sentinel”)
  • \n
\n
template <typename T>
class diagonals {
using matrix_t = std::vector<std::vector<T>>;

matrix_t& _matrix;

public:
diagonals(matrix_t& m)
: _matrix(m)
{
}
diagonals_iter begin()
{
/* TODO */
}
diagonals_iter end()
{
/* TODO */
}
};
\n

Now 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

We 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 “shortcut” 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

Iterating over diagonals

\n

Now 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 “main”\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

We 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

We will start by updating the begin and end to reflect our choice accordingly.

\n
diagonals_iter begin() { return diagonals_iter { _matrix, 0, 0 }; }
diagonals_iter end() { return diagonals_iter { _matrix, 0, _matrix.size() }; }
\n

For 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
note

You 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

Cool, let's leave the iterator itself to someone else, right?4

\n

Implementing the iterator over diagonals

\n

We 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
class diagonals_iter {
matrix_t& m;
std::size_t x;
std::size_t y;

public:
diagonals_iter(matrix_t& matrix, std::size_t x, std::size_t y)
: m(matrix)
, x(x)
, y(y)
{
}
};
\n

In this case we will be implementing a “simple” forward iterator, so we don't\nneed to implement a lot. Notably it will be:

\n
    \n
  • inequality operator (we need to know when we reach the end and have nothing to\niterate 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\nover)
  • \n
\n
class diagonals_iter {
matrix_t& m;
std::size_t x;
std::size_t y;

public:
diagonals_iter(matrix_t& matrix, std::size_t x, std::size_t y)
: m(matrix)
, x(x)
, y(y)
{
}

bool operator!=(const diagonals_iter& rhs) const
{
// iterators are not equal if they reference different matrices, or
// their positions differ
return m != rhs.m || x != rhs.x || y != rhs.y;
}

diagonals_iter& operator++()
{
if (y != 0) {
// iterating through diagonals down the first column
y++;
return *this;
}

// iterating the diagonals along the first row
x++;
if (x == m.front().size()) {
// switching to diagonals in the first column
x = 0;
y++;
}

return *this;
}

diagonal<T> operator*() const { return diagonal { m, x, y }; }
};
\n

Let'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
-        return m != rhs.m || x != rhs.x || y != rhs.y;
+ return x != rhs.x || y != rhs.y || m != rhs.m;
\n

Preincrementation is where the magic happens. If you have a better look, you can\nsee two branches of this operation:

\n
    \n
  1. When y != 0 (we're iterating over the diagonals in the first column)\nIn this case, we just bump the row and we're done.
  2. \n
  3. When y == 0 (we're iterating over the diagonals in the first row)\nIn this case, we bump the column and check if we haven't gotten out of bounds,\ni.e. the end of the first row. If we get out of the bounds, we're continuing\nwith the second diagonal in the first column.
  4. \n
\n

Dereferencing the iterator must “yield” 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

Implementing the diagonal itself

\n

After implementing the iterator over diagonals, we know that all we need to describe\na diagonal is the matrix itself and the “start” 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
template <typename T>
class diagonal {
using matrix_t = std::vector<std::vector<T>>;

matrix_t& matrix;
std::size_t x;
std::size_t y;

public:
diagonal(matrix_t& matrix, std::size_t x, std::size_t y)
: matrix(matrix)
, x(x)
, y(y)
{
}

diagonal_iter begin() const { return diagonal_iter { matrix, x, y }; }

diagonal_iter end() const
{
auto max_x = matrix[y].size();
auto max_y = matrix.size();

// we need to find the distance in which we get out of bounds (either in
// column or row)
auto steps = std::min(max_x - x, max_y - y);

return diagonal_iter { matrix, x + steps, y + steps };
}
};
\n

Initialization is rather simple, we just “keep” the stuff we get, begin is the\nsimplest, we just delegate.

\n

In case of the end, it gets more complicated. We need to know where is the “end”\nof the diagonal. Since end should point to the first element “after” the iterable,\nwe know that it's the first position of the iterator where either y becomes\nmatrix.size() or x becomes matrix[y].size(). Also we are moving along diagonal,\nduh, therefore we can deduce the first “position” 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

Now we just need to finish the iterator for the diagonal itself and we're done.

\n

Implementing diagonal_iter

\n

This 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 “in a nutshell” it means that we need to implement\nan iterator that can move in constant time along the diagonal in any amount of\nsteps.

\n

Let'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
\n

We will also add all the types that our iterator uses with the category of the\niterator, i.e. what interface it supports:

\n
class diagonal_iter {
// we need to keep reference to the matrix itself
matrix_t& m;

// we need to be able to tell our current position
std::size_t x;
std::size_t y;

public:
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = T*;
using reference = T&;
using iterator_category = std::random_access_iterator_tag;

diagonal_iter(matrix_t& matrix,
std::size_t x,
std::size_t y)
: m(matrix)
, x(x)
, y(y)
{
}

bool operator==(const diagonal_iter& rhs) const
{
return x == rhs.x && y == rhs.y && m == rhs.m;
}

diagonal_iter& operator++()
{
// we are moving along the diagonal, so we increment both ‹x› and ‹y› at
// the same time
x++;
y++;
return *this;
}

reference operator*() const { return m[y][x]; }
};
\n

This 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 _\naccess 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
\n

Let's fill them in:

\n
class diagonal_iter {
// we need to keep reference to the matrix itself
matrix_t& m;

// we need to be able to tell our current position
std::size_t x;
std::size_t y;

public:
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = T*;
using reference = T&;
using iterator_category = std::random_access_iterator_tag;

diagonal_iter(matrix_t& matrix,
std::size_t x,
std::size_t y)
: m(matrix)
, x(x)
, y(y)
{
}

bool operator==(const diagonal_iter& rhs) const
{
return x == rhs.x && y == rhs.y && m == rhs.m;
}

diagonal_iter& operator++()
{
// we are moving along the diagonal, so we increment both ‹x› and ‹y› at
// the same time
x++;
y++;
return *this;
}

reference operator*() const { return m[y][x]; }

// exactly opposite to the incrementation
diagonal_iter operator--()
{
x--;
y--;
return *this;
}

// moving ‹n› steps back is same as calling decrementation ‹n›-times, so we
// can just return a new iterator and subtract ‹n› from both coordinates in
// the matrix
diagonal_iter operator-(difference_type n) const
{
return diagonal_iter { m, x - n, y - n };
}

// here we assume that we are given two iterators on the same diagonal
difference_type operator-(const diagonal_iter& rhs) const
{
assert(m == rhs.m);
return x - rhs.x;
}

// counterpart of moving ‹n› steps backwards
diagonal_iter operator+(difference_type n) const
{
return diagonal_iter { m, x + n, y + n };
}

// we compare the coordinates, and also assume that those 2 iterators are
// lying on the same diagonal
bool operator<(const diagonal_iter& rhs) const
{
assert(m == rhs.m);
return x < rhs.x && y < rhs.y;
}
};
\n

At 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
/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]
__last = __next;
^
/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
std::__unguarded_linear_insert(__i,
^
/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
std::__insertion_sort(__first, __first + int(_S_threshold), __comp);
^
/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
std::__final_insertion_sort(__first, __last, __comp);
^
/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
std::__sort(__first, __last, __gnu_cxx::__ops::__iter_less_iter());
^
matrix-sort.cpp:161:18: note: in instantiation of function template specialization 'std::sort<diagonal<int>::diagonal_iter>' requested here
std::sort(d.begin(), d.end());
^
matrix-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>> &')
matrix_t& m;
^
/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]
std::__unguarded_linear_insert(__i,
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/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
std::__unguarded_insertion_sort(__first + int(_S_threshold), __last,
^
/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
std::__final_insertion_sort(__first, __last, __comp);
^
/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
std::__sort(__first, __last, __gnu_cxx::__ops::__iter_less_iter());
^
matrix-sort.cpp:161:18: note: in instantiation of function template specialization 'std::sort<diagonal<int>::diagonal_iter>' requested here
std::sort(d.begin(), d.end());
^
/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]
__unguarded_linear_insert(_RandomAccessIterator __last,
^
/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]
__last = __cut;
^
/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
std::__introsort_loop(__first, __last,
^
/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
std::__sort(__first, __last, __gnu_cxx::__ops::__iter_less_iter());
^
matrix-sort.cpp:161:18: note: in instantiation of function template specialization 'std::sort<diagonal<int>::diagonal_iter>' requested here
std::sort(d.begin(), d.end());
^
matrix-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>> &')
matrix_t& m;
^
\n

That's a lot of noise, isn't it? Let's focus on the important parts:

\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]

matrix-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>> &')
matrix_t& m;
^
\n

Ah! We have a reference in our iterator, and this prevents us from having a copy\nassignment operator (that is used “somewhere” in the sorting algorithm). Well…\nLet's just wrap it!

\n
# we need to keep a different type than reference
- matrix_t& m;
+ std::reference_wrapper<matrix_t> m;

# in comparison we need to get the reference out of the wrapper first
- return x == rhs.x && y == rhs.y && m == rhs.m;
+ return x == rhs.x && y == rhs.y && m.get() == rhs.m.get();

# same when we return a reference to the “cell” in the matrix
- reference operator*() const { return m[y][x]; }
+ reference operator*() const { return m.get()[y][x]; }

# and finally in the assertions that we set for the “distance” and “less than”
- assert(m == rhs.m);
+ assert(m.get() == rhs.m.get());
\n

We're done now! We have written an iterator over diagonals for a 2D vector. You can have a look at the final result here.

\n

Footnotes

\n
    \n
  1. \n

    just because I'm used to it and don't care about your opinion ;)

    \n
  2. \n
  3. \n

    exercise at your own risk

    \n
  4. \n
  5. \n

    me in 5 minutes in fact, but don't make me scared

    \n
  6. \n
  7. \n

    me in the next section…

    \n
  8. \n
\n
", + "content_html": "

Let's try to solve one of the LeetCode challenges in easy and hard mode at the\nsame time.

\n\n

Problem description

\n

A 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],\nmat[3][1], and mat[4][2].

\n

Given an m x n matrix mat of integers, sort each matrix diagonal in ascending\norder and return the resulting matrix.

\n

Example

\n

\"Image

\n

Skeleton and initial adjustments

\n

We are given the following skeleton for the C++ and the given challenge:

\n
class Solution {
public:
vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {

}
};
\n

The 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 namespaces1 and also adding few tests:

\n
#include <cassert>
#include <vector>

using matrix = std::vector<std::vector<int>>;

class Solution {
public:
matrix diagonalSort(matrix& mat)
{
}
};

static void test_case_1()
{
// Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]
// Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]

Solution s;
assert((s.diagonalSort(std::vector { std::vector { 3, 3, 1, 1 },
std::vector { 2, 2, 1, 2 },
std::vector { 1, 1, 1, 2 } })
== std::vector { std::vector { 1, 1, 1, 1 },
std::vector { 1, 2, 2, 2 },
std::vector { 1, 2, 3, 3 } }));
}

static void test_case_2()
{
// Input: mat =
// [[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]]
// Output:
// [[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]]

Solution s;
assert((s.diagonalSort(std::vector { std::vector { 11, 25, 66, 1, 69, 7 },
std::vector { 23, 55, 17, 45, 15, 52 },
std::vector { 75, 31, 36, 44, 58, 8 },
std::vector { 22, 27, 33, 25, 68, 4 },
std::vector { 84, 28, 14, 11, 5, 50 } })
== std::vector { std::vector { 5, 17, 4, 1, 52, 7 },
std::vector { 11, 11, 25, 45, 8, 69 },
std::vector { 14, 23, 25, 44, 58, 15 },
std::vector { 22, 27, 31, 36, 50, 66 },
std::vector { 84, 28, 75, 33, 55, 68 } }));
}

int main()
{
test_case_1();
test_case_2();

return 0;
}
\n

We 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 “shut up” we will just return\nthe input for now:

\n
-    matrix diagonalSort(matrix& mat)
+ matrix diagonalSort(matrix mat)
{
+ return mat;
}
\n

Now, we get the copy and we're good to go.

\n

Naïve solution

\n

As you may know, C++ offers a plethora of functions that can be used to your\nadvantage, given that you know how to “bend” the data structures accordingly.

\n

What does that mean for us? Well, we have an std::sort, we can use it, right?\nLet's have a look at it:

\n
template< class RandomIt >
void sort( RandomIt first, RandomIt last );
\n

This 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… we can sort just »one« diagonal without doing much work\non our end.

\n

What 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\niterator and allows swapping its values at the same time.

\n
Random access iterator

What is the random access iterator though? We can find it in a documentation\nand see the following description:

\n

A LegacyRandomAccessIterator is a LegacyBidirectionalIterator\nthat can be moved to point to any element in constant time.

\n

After 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. “compiler-assisted development2 if you will ;)

\n

Now 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 else3. And that way we get

\n
matrix diagonalSort(matrix mat)
{
// we iterate over the diagonals
for (auto d : diagonals(mat)) {
// and we sort each diagonal
std::sort(d.begin(), d.end());
}

// we take the matrix by copy, so we can sort in-situ and return the copy
// that we sorted
return mat;
}
\n

This solution looks very simple, doesn't it? Well, cause it is.\nLet's try compiling it:

\n
matrix-sort.cpp:11:23: error: use of undeclared identifier 'diagonals' [clang-diagnostic-error]
for (auto d : diagonals(mat)) {
^
Found compiler error(s).
make: *** [makefile:14: tidy] Error 1
\n

OK, 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

Implementing the diagonals

\n

Cool, 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\ndiagonals 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

As I said, we need to be able to

\n
    \n
  • construct the object
  • \n
  • get the beginning
  • \n
  • get the end (the “sentinel”)
  • \n
\n
template <typename T>
class diagonals {
using matrix_t = std::vector<std::vector<T>>;

matrix_t& _matrix;

public:
diagonals(matrix_t& m)
: _matrix(m)
{
}
diagonals_iter begin()
{
/* TODO */
}
diagonals_iter end()
{
/* TODO */
}
};
\n

Now 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

We 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 “shortcut” 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

Iterating over diagonals

\n

Now 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 “main”\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

We 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

We will start by updating the begin and end to reflect our choice accordingly.

\n
diagonals_iter begin() { return diagonals_iter { _matrix, 0, 0 }; }
diagonals_iter end() { return diagonals_iter { _matrix, 0, _matrix.size() }; }
\n

For 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
note

You 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

Cool, let's leave the iterator itself to someone else, right?4

\n

Implementing the iterator over diagonals

\n

We 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
class diagonals_iter {
matrix_t& m;
std::size_t x;
std::size_t y;

public:
diagonals_iter(matrix_t& matrix, std::size_t x, std::size_t y)
: m(matrix)
, x(x)
, y(y)
{
}
};
\n

In this case we will be implementing a “simple” forward iterator, so we don't\nneed to implement a lot. Notably it will be:

\n
    \n
  • inequality operator (we need to know when we reach the end and have nothing to\niterate 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\nover)
  • \n
\n
class diagonals_iter {
matrix_t& m;
std::size_t x;
std::size_t y;

public:
diagonals_iter(matrix_t& matrix, std::size_t x, std::size_t y)
: m(matrix)
, x(x)
, y(y)
{
}

bool operator!=(const diagonals_iter& rhs) const
{
// iterators are not equal if they reference different matrices, or
// their positions differ
return m != rhs.m || x != rhs.x || y != rhs.y;
}

diagonals_iter& operator++()
{
if (y != 0) {
// iterating through diagonals down the first column
y++;
return *this;
}

// iterating the diagonals along the first row
x++;
if (x == m.front().size()) {
// switching to diagonals in the first column
x = 0;
y++;
}

return *this;
}

diagonal<T> operator*() const { return diagonal { m, x, y }; }
};
\n

Let'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
-        return m != rhs.m || x != rhs.x || y != rhs.y;
+ return x != rhs.x || y != rhs.y || m != rhs.m;
\n

Preincrementation is where the magic happens. If you have a better look, you can\nsee two branches of this operation:

\n
    \n
  1. When y != 0 (we're iterating over the diagonals in the first column)\nIn this case, we just bump the row and we're done.
  2. \n
  3. When y == 0 (we're iterating over the diagonals in the first row)\nIn this case, we bump the column and check if we haven't gotten out of bounds,\ni.e. the end of the first row. If we get out of the bounds, we're continuing\nwith the second diagonal in the first column.
  4. \n
\n

Dereferencing the iterator must “yield” 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

Implementing the diagonal itself

\n

After implementing the iterator over diagonals, we know that all we need to describe\na diagonal is the matrix itself and the “start” 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
template <typename T>
class diagonal {
using matrix_t = std::vector<std::vector<T>>;

matrix_t& matrix;
std::size_t x;
std::size_t y;

public:
diagonal(matrix_t& matrix, std::size_t x, std::size_t y)
: matrix(matrix)
, x(x)
, y(y)
{
}

diagonal_iter begin() const { return diagonal_iter { matrix, x, y }; }

diagonal_iter end() const
{
auto max_x = matrix[y].size();
auto max_y = matrix.size();

// we need to find the distance in which we get out of bounds (either in
// column or row)
auto steps = std::min(max_x - x, max_y - y);

return diagonal_iter { matrix, x + steps, y + steps };
}
};
\n

Initialization is rather simple, we just “keep” the stuff we get, begin is the\nsimplest, we just delegate.

\n

In case of the end, it gets more complicated. We need to know where is the “end”\nof the diagonal. Since end should point to the first element “after” the iterable,\nwe know that it's the first position of the iterator where either y becomes\nmatrix.size() or x becomes matrix[y].size(). Also we are moving along diagonal,\nduh, therefore we can deduce the first “position” 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

Now we just need to finish the iterator for the diagonal itself and we're done.

\n

Implementing diagonal_iter

\n

This 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 “in a nutshell” it means that we need to implement\nan iterator that can move in constant time along the diagonal in any amount of\nsteps.

\n

Let'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
\n

We will also add all the types that our iterator uses with the category of the\niterator, i.e. what interface it supports:

\n
class diagonal_iter {
// we need to keep reference to the matrix itself
matrix_t& m;

// we need to be able to tell our current position
std::size_t x;
std::size_t y;

public:
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = T*;
using reference = T&;
using iterator_category = std::random_access_iterator_tag;

diagonal_iter(matrix_t& matrix,
std::size_t x,
std::size_t y)
: m(matrix)
, x(x)
, y(y)
{
}

bool operator==(const diagonal_iter& rhs) const
{
return x == rhs.x && y == rhs.y && m == rhs.m;
}

diagonal_iter& operator++()
{
// we are moving along the diagonal, so we increment both ‹x› and ‹y› at
// the same time
x++;
y++;
return *this;
}

reference operator*() const { return m[y][x]; }
};
\n

This 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 _\naccess 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
\n

Let's fill them in:

\n
class diagonal_iter {
// we need to keep reference to the matrix itself
matrix_t& m;

// we need to be able to tell our current position
std::size_t x;
std::size_t y;

public:
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = T*;
using reference = T&;
using iterator_category = std::random_access_iterator_tag;

diagonal_iter(matrix_t& matrix,
std::size_t x,
std::size_t y)
: m(matrix)
, x(x)
, y(y)
{
}

bool operator==(const diagonal_iter& rhs) const
{
return x == rhs.x && y == rhs.y && m == rhs.m;
}

diagonal_iter& operator++()
{
// we are moving along the diagonal, so we increment both ‹x› and ‹y› at
// the same time
x++;
y++;
return *this;
}

reference operator*() const { return m[y][x]; }

// exactly opposite to the incrementation
diagonal_iter operator--()
{
x--;
y--;
return *this;
}

// moving ‹n› steps back is same as calling decrementation ‹n›-times, so we
// can just return a new iterator and subtract ‹n› from both coordinates in
// the matrix
diagonal_iter operator-(difference_type n) const
{
return diagonal_iter { m, x - n, y - n };
}

// here we assume that we are given two iterators on the same diagonal
difference_type operator-(const diagonal_iter& rhs) const
{
assert(m == rhs.m);
return x - rhs.x;
}

// counterpart of moving ‹n› steps backwards
diagonal_iter operator+(difference_type n) const
{
return diagonal_iter { m, x + n, y + n };
}

// we compare the coordinates, and also assume that those 2 iterators are
// lying on the same diagonal
bool operator<(const diagonal_iter& rhs) const
{
assert(m == rhs.m);
return x < rhs.x && y < rhs.y;
}
};
\n

At 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
/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]
__last = __next;
^
/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
std::__unguarded_linear_insert(__i,
^
/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
std::__insertion_sort(__first, __first + int(_S_threshold), __comp);
^
/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
std::__final_insertion_sort(__first, __last, __comp);
^
/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
std::__sort(__first, __last, __gnu_cxx::__ops::__iter_less_iter());
^
matrix-sort.cpp:161:18: note: in instantiation of function template specialization 'std::sort<diagonal<int>::diagonal_iter>' requested here
std::sort(d.begin(), d.end());
^
matrix-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>> &')
matrix_t& m;
^
/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]
std::__unguarded_linear_insert(__i,
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/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
std::__unguarded_insertion_sort(__first + int(_S_threshold), __last,
^
/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
std::__final_insertion_sort(__first, __last, __comp);
^
/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
std::__sort(__first, __last, __gnu_cxx::__ops::__iter_less_iter());
^
matrix-sort.cpp:161:18: note: in instantiation of function template specialization 'std::sort<diagonal<int>::diagonal_iter>' requested here
std::sort(d.begin(), d.end());
^
/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]
__unguarded_linear_insert(_RandomAccessIterator __last,
^
/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]
__last = __cut;
^
/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
std::__introsort_loop(__first, __last,
^
/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
std::__sort(__first, __last, __gnu_cxx::__ops::__iter_less_iter());
^
matrix-sort.cpp:161:18: note: in instantiation of function template specialization 'std::sort<diagonal<int>::diagonal_iter>' requested here
std::sort(d.begin(), d.end());
^
matrix-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>> &')
matrix_t& m;
^
\n

That's a lot of noise, isn't it? Let's focus on the important parts:

\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]

matrix-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>> &')
matrix_t& m;
^
\n

Ah! We have a reference in our iterator, and this prevents us from having a copy\nassignment operator (that is used “somewhere” in the sorting algorithm). Well…\nLet's just wrap it!

\n
# we need to keep a different type than reference
- matrix_t& m;
+ std::reference_wrapper<matrix_t> m;

# in comparison we need to get the reference out of the wrapper first
- return x == rhs.x && y == rhs.y && m == rhs.m;
+ return x == rhs.x && y == rhs.y && m.get() == rhs.m.get();

# same when we return a reference to the “cell” in the matrix
- reference operator*() const { return m[y][x]; }
+ reference operator*() const { return m.get()[y][x]; }

# and finally in the assertions that we set for the “distance” and “less than”
- assert(m == rhs.m);
+ assert(m.get() == rhs.m.get());
\n

We're done now! We have written an iterator over diagonals for a 2D vector. You can have a look at the final result here.

\n

Footnotes

\n
    \n
  1. \n

    just because I'm used to it and don't care about your opinion ;)

    \n
  2. \n
  3. \n

    exercise at your own risk

    \n
  4. \n
  5. \n

    me in 5 minutes in fact, but don't make me scared

    \n
  6. \n
  7. \n

    me in the next section…

    \n
  8. \n
\n
", "url": "https://blog.mfocko.xyz/blog/leetcode/sort-diagonally", "title": "Sort the matrix diagonally", "summary": "Compiler assisted development.", @@ -76,7 +76,7 @@ }, { "id": "https://blog.mfocko.xyz/blog/aoc-2022/2nd-week", - "content_html": "

Let's go through the second week of Advent of Code in Rust.

\n

Day 8: Treetop Tree House

\n
tl;dr

We 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

Nothing 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 Vecs. 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

I'm getting familiar with Rust and starting to “abuse” it… While doing so, I'm\nalso uncovering some “features” that I don't really like. Therefore I will mark\nall of my rants with thicc «↯» mark and will try to “lock” them into their\nown “box of hell”.

\n

Swapping indices

\n

Relatively simple implementation, just take the values, swap them and return new\nvector.

\n
impl<T: Copy> Vector2D<T> {
pub fn swap(&self) -> Self {
Self {
x: self.y,
y: self.x,
}
}
}
\n

Pretty 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

Indexing Vec

\n

I will start with the indexing, cause bound-checking is a bit more… complicated\nthan I would like to.

\n
pub fn index<'a, T, U>(v: &'a [Vec<U>], idx: &Vector2D<T>) -> &'a U
where
usize: TryFrom<T>,
<usize as TryFrom<T>>::Error: Debug,
T: Copy,
{
let (x, y): (usize, usize) = (idx.x.try_into().unwrap(), idx.y.try_into().unwrap());
&v[y][x]
}
\n

Let's talk about this mess… 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

The type signature of the function is where the fun is at 😉 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,\ni.e. can be printed in some way or other

\n
\n

T: Copy is required by .try_into() which takes T by-value.

\n

And now we are left only with the first line of the definition.

\n
note

Skilled Rustaceans might notice that this implementation is rather flaky and can\nbreak in multiple places at once. I'll get back to it…

\n

Let's split it in multiple parts:

\n
    \n
  • v: &'a [Vec<U>] represents the 2D Vec, we are indexing, Vec implements\nSlice trait and clippy recommends using &[T] to &Vec<T>, exact details\nare unknown to me
  • \n
  • idx: &Vector2D<T> represents the indices which we use, we take them by\nreference to avoid an unnecessary copy
  • \n
  • -> &'a U means that we are returning a reference to some value of type U.\nNow the question is what does the 'a mean, we can also see it as a generic\ntype declared along T and U. And the answer is relatively simple, 'a\nrepresents a lifetime. We take the v by a reference and return a reference,\nborrow checker validates all of the borrows (or references), so we need to\nspecify that our returned value has the same lifetime as the vector we have\ntaken by a reference, i.e. returned reference must live at least as long as the\nv. This way we can “be sure” that the returned reference is valid.
  • \n
\n
Issues
\n

First 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
pub fn index_mut<'a, T, U>(v: &'a mut [Vec<U>], idx: &Vector2D<T>) -> &'a mut U
where
usize: TryFrom<T>,
<usize as TryFrom<T>>::Error: Debug,
T: Copy,
{
let (x, y): (usize, usize) = (idx.x.try_into().unwrap(), idx.y.try_into().unwrap());
&mut v[y][x]
}
\n
«↯» Why can't we use one function?

When 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].

However, 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 “built-in” types.

Another part of this rabbit hole is trait SliceIndex<T> that is of a relevance\nbecause of

impl<T, I> Index<I> for [T]
where
I: SliceIndex<[T]>

impl<T, I, A> Index<I> for Vec<T, A>
where
I: SliceIndex<[T]>,
A: Allocator

impl<T, I, const N: usize> Index<I> for [T; N]
where
[T]: Index<I>

In 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

Another 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
pub fn index<'a, C, T>(v: &'a [C], idx: &Vector2D<T>) -> &'a C::Output
where
usize: TryFrom<T>,
<usize as TryFrom<T>>::Error: Debug,
T: Copy,
C: Index<usize>
{
let (x, y): (usize, usize) = (idx.x.try_into().unwrap(), idx.y.try_into().unwrap());
&v[y][x]
}
\n

Given this, we can also give a more meaningful typename for indexing type, such\nas I.

\n

Checking bounds

\n

Now we can get to the boundary checks, it is very similar, but a more… 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

So how can we approach this then? Well… we will convert the bounds instead of\nthe indices and that lead us to:

\n
pub fn in_range<T, U>(v: &[Vec<U>], idx: &Vector2D<T>) -> bool
where
usize: TryInto<T>,
<usize as TryInto<T>>::Error: Debug,
T: PartialOrd + Copy,
{
idx.y >= 0.try_into().unwrap()
&& idx.y < v.len().try_into().unwrap()
&& idx.x >= 0.try_into().unwrap()
&& idx.x
< v[TryInto::<usize>::try_into(idx.y).unwrap()]
.len()
.try_into()
.unwrap()
}
\n

You 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
pub fn in_range<T, U>(v: &[Vec<U>], idx: &Vector2D<T>) -> bool
where
T: Copy,
usize: TryFrom<T>,
{
usize::try_from(idx.y)
.and_then(|y| usize::try_from(idx.x).map(|x| y < v.len() && x < v[y].len()))
.unwrap_or(false)
}
\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

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

We call and_then on that result, let's have a look at the type signature of\nand_then, IMO it explains more than enough:

\n
pub fn and_then<U, F>(self, op: F) -> Result<U, E>
where
F: FnOnce(T) -> Result<U, E>
\n

OK… 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
\n

We 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
pub fn map<U, F>(self, op: F) -> Result<U, E>
where
F: FnOnce(T) -> U
\n

Huh… map performs an operation that cannot fail. And finally we use\nunwrap_or which takes the value from result, or in case of an error returns the\ndefault that we define.

\n

How 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

Solution

\n

Relatively simple, you just need follow the rules and not get too smart, otherwise\nit will get back at you.

\n

Day 9: Rope Bridge

\n
tl;dr

We get a rope with knots and we want to track how many different positions are\nvisited with the rope's tail.

\n

By 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 “simplify” 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
    \n
  • parsing
  • \n
  • part 1 & 2
  • \n
  • running on sample / input
  • \n
  • tests
  • \n
\n

Parsing 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

Let'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
pub trait Solution<Input, Output: Display> {
fn parse_input<P: AsRef<Path>>(pathname: P) -> Input;

fn part_1(input: &Input) -> Output;
fn part_2(input: &Input) -> Output;
}
\n

This 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

Now 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
fn run(type_of_input: &str) -> Result<()>
where
Self: Sized,
{
tracing_subscriber::fmt()
.with_env_filter(EnvFilter::from_default_env())
.with_target(false)
.with_file(true)
.with_line_number(true)
.without_time()
.compact()
.init();
color_eyre::install()?;

let input = Self::parse_input(format!(\"{}s/{}.txt\", type_of_input, Self::day()));

info!(\"Part 1: {}\", Self::part_1(&input));
info!(\"Part 2: {}\", Self::part_2(&input));

Ok(())
}

fn main() -> Result<()>
where
Self: Sized,
{
Self::run(\"input\")
}
\n

This 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\ninfo! and format string there.

\n

Now we can get to first of the nasty things we are going to do… And it is the\nday() 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
fn day() -> String {
let mut day = String::from(type_name::<Self>().split(\"::\").next().unwrap());
day.make_ascii_lowercase();

day.to_string()
}
\n
type_name

This feature is still experimental and considered to be internal, it is not\nadvised to use it any production code.

\n

And now we can get to the nastiest stuff 😩 We will generate the tests!

\n

We want to be able to generate tests for sample input in a following way:

\n
test_sample!(day_01, Day01, 42, 69);
\n

There's not much we can do, so we will write a macro to generate the tests for us.

\n
#[macro_export]
macro_rules! test_sample {
($mod_name:ident, $day_struct:tt, $part_1:expr, $part_2:expr) => {
#[cfg(test)]
mod $mod_name {
use super::*;

#[test]
fn test_part_1() {
let sample =
$day_struct::parse_input(&format!(\"samples/{}.txt\", $day_struct::day()));
assert_eq!($day_struct::part_1(&sample), $part_1);
}

#[test]
fn test_part_2() {
let sample =
$day_struct::parse_input(&format!(\"samples/{}.txt\", $day_struct::day()));
assert_eq!($day_struct::part_2(&sample), $part_2);
}
}
};
}
\n

We 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 “type” of the parameters for the macro. All\nparameters have their name prefixed with $ sign and you can define various “forms”\nof your macro. Let's go through it!

\n

We have following parameters:

\n
    \n
  • $mod_name which represents the name for the module with tests, it is typed\nwith 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\nwith tt which represents a token tree, in our case it is a type.
  • \n
  • $part_X represents the expected output for the Xth part and is of type expr\nwhich literally means an expression.
  • \n
\n

Apart 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
use aoc_2022::*;

type Input = String;
type Output = String;

struct DayXX;
impl Solution<Input, Output> for DayXX {
fn parse_input<P: AsRef<Path>>(pathname: P) -> Input {
file_to_string(pathname)
}

fn part_1(input: &Input) -> Output {
todo!()
}

fn part_2(input: &Input) -> Output {
todo!()
}
}

fn main() -> Result<()> {
// DayXX::run(\"sample\")
DayXX::main()
}

// test_sample!(day_XX, DayXX, , );
\n

Solution

\n

Not much to talk about, it is relatively easy to simulate.

\n

Day 10: Cathode-Ray Tube

\n
tl;dr

Emulating basic arithmetic operations on a CPU and drawing on CRT based on the\nCPU's accumulator.

\n

In 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

Problem is relatively simple and consists of simulating a CPU, I have approached\nit in a following way:

\n
fn evaluate_instructions(instructions: &[Instruction], mut out: Output) -> Output {
instructions
.iter()
.fold(State::new(), |state, instruction| {
state.execute(instruction, &mut out)
});

out
}
\n

We 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

You 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
tip

We could've seen something like this with the Result<T, E> type that can be\ndefined as

enum Result<T, E> {
Ok(T),
Err(E)
}
What does that mean though?

When 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:

match do_something(x) {
Ok(y) => {
println!(\"SUCCESS: {}\", y);
},
Err(y) => {
eprintln!(\"ERROR: {}\", y);
}
}
\n

My solution has a following outline:

\n
fn execute(&self, i: &Instruction, output: &mut Output) -> State {
// execute the instruction

// collect results if necessary
match output {
Output::Part1(x) => self.execute_part_1(y, x),
Output::Part2(x) => self.execute_part_2(y, x),
}

// return the obtained state
new_state
}
\n

You 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

The dirty and ingenious thing is that xs 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\nacross all iterations of fold.

\n
\n

Solution

\n

Similar to Day 9, but there are some technical details that can get you.

\n

Day 11: Monkey in the Middle

\n
tl;dr

Simulation of monkeys throwing stuff around and measuring your stress levels\nwhile your stuff is being passed around.

\n

I think I decided to use regular expressions here for the first time, cause\nparsing the input was a pain.

\n

Also I didn't expect to implement Euclidean algorithm in Rust…

\n

Solution

\n

Again, 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

Day 12: Hill Climbing Algorithm

\n
tl;dr

Finding shortest path up the hill and also shortest path down to the ground while\nalso rolling down the hill…

\n

As 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
fn bfs<F, G>(
graph: &[Vec<char>], start: &Position, has_edge: F, is_target: G
) -> Option<usize>
where
F: Fn(&[Vec<char>], &Position, &Position) -> bool,
G: Fn(&[Vec<char>], &Position) -> bool
\n

We 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

This was easy! And that is not very usual in Rust once you want to pass around\nfunctions. 👀

\n

Solution

\n

Looking for the shortest path… 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=1d = 1d=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

Day 13: Distress Signal

\n
tl;dr

Processing packets with structured data from the distress signal.

\n

You 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
impl Display for Packet {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Packet::Integer(x) => write!(f, \"{x}\"),
Packet::List(lst) => write!(f, \"[{}]\", lst.iter().map(|p| format!(\"{p}\")).join(\",\")),
}
}
}
\n

Solution

\n

A lot of technical details… Parsing is nasty too…

\n

Day 14: Regolith Reservoir

\n
tl;dr

Let's simulate falling sand grain-by-grain.

\n

Again, 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

Solution

\n

Tedious.

\n

Post Mortem

\n

Indexing

\n

I 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
note

I 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

It's relatively straightforward…

\n
impl<I, C> Index<Vector2D<I>> for [C]
where
I: Copy + TryInto<usize>,
<I as TryInto<usize>>::Error: Debug,
C: Index<usize>,
{
type Output = C::Output;

fn index(&self, index: Vector2D<I>) -> &Self::Output {
let (x, y): (usize, usize) =
(index.x.try_into().unwrap(), index.y.try_into().unwrap());
&self[y][x]
}
}

impl<I, C> IndexMut<Vector2D<I>> for [C]
where
I: Copy + TryInto<usize>,
<I as TryInto<usize>>::Error: Debug,
C: IndexMut<usize>,
{
fn index_mut(&mut self, index: Vector2D<I>) -> &mut Self::Output {
let (x, y): (usize, usize) =
(index.x.try_into().unwrap(), index.y.try_into().unwrap());
&mut self[y][x]
}
}
\n

We 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
note

I 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.

Also implementing TryFrom automatically provides you with a TryInto trait,\nsince it is relatively easy to implement. Just compare the following:

pub trait TryFrom<T>: Sized {
type Error;

fn try_from(value: T) -> Result<Self, Self::Error>;
}

pub trait TryInto<T>: Sized {
type Error;

fn try_into(self) -> Result<T, Self::Error>;
}
\n

OK, so we have our trait implemented, we should be able to use container[index],\nright? Yes… but actually no 😦

\n
error[E0277]: the type `[std::vec::Vec<i8>]` cannot be indexed by `aoc_2022::Vector2D<usize>`
--> src/bin/day08.rs:26:18
|
26 | if trees[pos] > tallest {
| ^^^ slice indices are of type `usize` or ranges of `usize`
|
= help: the trait `std::slice::SliceIndex<[std::vec::Vec<i8>]>` is not implemented for `aoc_2022::Vector2D<usize>`
= note: required for `std::vec::Vec<std::vec::Vec<i8>>` to implement `std::ops::Index<aoc_2022::Vector2D<usize>>`

error[E0277]: the type `[std::vec::Vec<i8>]` cannot be indexed by `aoc_2022::Vector2D<usize>`
--> src/bin/day08.rs:30:28
|
30 | max(tallest, trees[pos])
| ^^^ slice indices are of type `usize` or ranges of `usize`
|
= help: the trait `std::slice::SliceIndex<[std::vec::Vec<i8>]>` is not implemented for `aoc_2022::Vector2D<usize>`
= note: required for `std::vec::Vec<std::vec::Vec<i8>>` to implement `std::ops::Index<aoc_2022::Vector2D<usize>>`

error[E0277]: the type `[std::vec::Vec<i8>]` cannot be indexed by `aoc_2022::Vector2D<isize>`
--> src/bin/day08.rs:52:28
|
52 | let max_height = trees[position];
| ^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
|
= help: the trait `std::slice::SliceIndex<[std::vec::Vec<i8>]>` is not implemented for `aoc_2022::Vector2D<isize>`
= note: required for `std::vec::Vec<std::vec::Vec<i8>>` to implement `std::ops::Index<aoc_2022::Vector2D<isize>>`
\n

Why? 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… we don't implement Index and IndexMut for\nthose. Just for the slices. 🤯 What are we going to do about it?

\n

We can either start copy-pasting or be smarter about it… 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

Implementing the macro can be done in a following way:

\n
macro_rules! generate_indices {
($container:ty) => {
impl<I, C> Index<Vector2D<I>> for $container
where
I: Copy + TryInto<usize>,
<I as TryInto<usize>>::Error: Debug,
C: Index<usize>,
{
type Output = C::Output;

fn index(&self, index: Vector2D<I>) -> &Self::Output {
let (x, y): (usize, usize) =
(index.x.try_into().unwrap(), index.y.try_into().unwrap());
&self[y][x]
}
}

impl<I, C> IndexMut<Vector2D<I>> for $container
where
I: Copy + TryInto<usize>,
<I as TryInto<usize>>::Error: Debug,
C: IndexMut<usize>,
{
fn index_mut(&mut self, index: Vector2D<I>) -> &mut Self::Output {
let (x, y): (usize, usize) =
(index.x.try_into().unwrap(), index.y.try_into().unwrap());
&mut self[y][x]
}
}
};
}
\n

And now we can simply do

\n
generate_indices!(VecDeque<C>);
generate_indices!([C]);
generate_indices!(Vec<C>);
// generate_indices!([C; N], const N: usize);
\n

The last type (I took the inspiration from the implementations of the Index and\nIndexMut 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
note

If I were to use 2D-indexing over [C; N] slices, I'd probably just go with the\ncopy-paste, cause the cost of this “monstrosity” outweighs the benefits of no DRY.

\n

Cause of the problem

\n

This 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
fn get_sum(nums: &Vec<i32>) -> i32 {
nums.iter().sum()
}

fn main() {
let nums = vec![1, 2, 3];
println!(\"Sum: {}\", get_sum(&nums));
}
\n

and you run clippy on it, you will get

\n
Checking playground v0.0.1 (/playground)
warning: writing `&Vec` instead of `&[_]` involves a new object where a slice will do
--> src/main.rs:1:18
|
1 | fn get_sum(nums: &Vec<i32>) -> i32 {
| ^^^^^^^^^ help: change this to: `&[i32]`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#ptr_arg
= note: `#[warn(clippy::ptr_arg)]` on by default

warning: `playground` (bin \"playground\") generated 1 warning
Finished dev [unoptimized + debuginfo] target(s) in 0.61s
\n

However, if you introduce a type alias, such as

\n
type Numbers = Vec<i32>;
\n

Then clippy won't say anything, cause there is literally nothing to suggest.\nHowever the outcome is not the same…

", + "content_html": "

Let's go through the second week of Advent of Code in Rust.

\n

Day 8: Treetop Tree House

\n
tl;dr

We 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

Nothing 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 Vecs. 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

I'm getting familiar with Rust and starting to “abuse” it… While doing so, I'm\nalso uncovering some “features” that I don't really like. Therefore I will mark\nall of my rants with thicc «↯» mark and will try to “lock” them into their\nown “box of hell”.

\n

Swapping indices

\n

Relatively simple implementation, just take the values, swap them and return new\nvector.

\n
impl<T: Copy> Vector2D<T> {
pub fn swap(&self) -> Self {
Self {
x: self.y,
y: self.x,
}
}
}
\n

Pretty 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

Indexing Vec

\n

I will start with the indexing, cause bound-checking is a bit more… complicated\nthan I would like to.

\n
pub fn index<'a, T, U>(v: &'a [Vec<U>], idx: &Vector2D<T>) -> &'a U
where
usize: TryFrom<T>,
<usize as TryFrom<T>>::Error: Debug,
T: Copy,
{
let (x, y): (usize, usize) = (idx.x.try_into().unwrap(), idx.y.try_into().unwrap());
&v[y][x]
}
\n

Let's talk about this mess… 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

The type signature of the function is where the fun is at 😉 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,\ni.e. can be printed in some way or other

\n
\n

T: Copy is required by .try_into() which takes T by-value.

\n

And now we are left only with the first line of the definition.

\n
note

Skilled Rustaceans might notice that this implementation is rather flaky and can\nbreak in multiple places at once. I'll get back to it…

\n

Let's split it in multiple parts:

\n
    \n
  • v: &'a [Vec<U>] represents the 2D Vec, we are indexing, Vec implements\nSlice trait and clippy recommends using &[T] to &Vec<T>, exact details\nare unknown to me
  • \n
  • idx: &Vector2D<T> represents the indices which we use, we take them by\nreference to avoid an unnecessary copy
  • \n
  • -> &'a U means that we are returning a reference to some value of type U.\nNow the question is what does the 'a mean, we can also see it as a generic\ntype declared along T and U. And the answer is relatively simple, 'a\nrepresents a lifetime. We take the v by a reference and return a reference,\nborrow checker validates all of the borrows (or references), so we need to\nspecify that our returned value has the same lifetime as the vector we have\ntaken by a reference, i.e. returned reference must live at least as long as the\nv. This way we can “be sure” that the returned reference is valid.
  • \n
\n
Issues
\n

First 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
pub fn index_mut<'a, T, U>(v: &'a mut [Vec<U>], idx: &Vector2D<T>) -> &'a mut U
where
usize: TryFrom<T>,
<usize as TryFrom<T>>::Error: Debug,
T: Copy,
{
let (x, y): (usize, usize) = (idx.x.try_into().unwrap(), idx.y.try_into().unwrap());
&mut v[y][x]
}
\n
«↯» Why can't we use one function?

When 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].

However, 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 “built-in” types.

Another part of this rabbit hole is trait SliceIndex<T> that is of a relevance\nbecause of

impl<T, I> Index<I> for [T]
where
I: SliceIndex<[T]>

impl<T, I, A> Index<I> for Vec<T, A>
where
I: SliceIndex<[T]>,
A: Allocator

impl<T, I, const N: usize> Index<I> for [T; N]
where
[T]: Index<I>

In 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

Another 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
pub fn index<'a, C, T>(v: &'a [C], idx: &Vector2D<T>) -> &'a C::Output
where
usize: TryFrom<T>,
<usize as TryFrom<T>>::Error: Debug,
T: Copy,
C: Index<usize>
{
let (x, y): (usize, usize) = (idx.x.try_into().unwrap(), idx.y.try_into().unwrap());
&v[y][x]
}
\n

Given this, we can also give a more meaningful typename for indexing type, such\nas I.

\n

Checking bounds

\n

Now we can get to the boundary checks, it is very similar, but a more… 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

So how can we approach this then? Well… we will convert the bounds instead of\nthe indices and that lead us to:

\n
pub fn in_range<T, U>(v: &[Vec<U>], idx: &Vector2D<T>) -> bool
where
usize: TryInto<T>,
<usize as TryInto<T>>::Error: Debug,
T: PartialOrd + Copy,
{
idx.y >= 0.try_into().unwrap()
&& idx.y < v.len().try_into().unwrap()
&& idx.x >= 0.try_into().unwrap()
&& idx.x
< v[TryInto::<usize>::try_into(idx.y).unwrap()]
.len()
.try_into()
.unwrap()
}
\n

You 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
pub fn in_range<T, U>(v: &[Vec<U>], idx: &Vector2D<T>) -> bool
where
T: Copy,
usize: TryFrom<T>,
{
usize::try_from(idx.y)
.and_then(|y| usize::try_from(idx.x).map(|x| y < v.len() && x < v[y].len()))
.unwrap_or(false)
}
\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

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

We call and_then on that result, let's have a look at the type signature of\nand_then, IMO it explains more than enough:

\n
pub fn and_then<U, F>(self, op: F) -> Result<U, E>
where
F: FnOnce(T) -> Result<U, E>
\n

OK… 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
\n

We 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
pub fn map<U, F>(self, op: F) -> Result<U, E>
where
F: FnOnce(T) -> U
\n

Huh… map performs an operation that cannot fail. And finally we use\nunwrap_or which takes the value from result, or in case of an error returns the\ndefault that we define.

\n

How 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

Solution

\n

Relatively simple, you just need follow the rules and not get too smart, otherwise\nit will get back at you.

\n

Day 9: Rope Bridge

\n
tl;dr

We get a rope with knots and we want to track how many different positions are\nvisited with the rope's tail.

\n

By 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 “simplify” 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
    \n
  • parsing
  • \n
  • part 1 & 2
  • \n
  • running on sample / input
  • \n
  • tests
  • \n
\n

Parsing 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

Let'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
pub trait Solution<Input, Output: Display> {
fn parse_input<P: AsRef<Path>>(pathname: P) -> Input;

fn part_1(input: &Input) -> Output;
fn part_2(input: &Input) -> Output;
}
\n

This 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

Now 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
fn run(type_of_input: &str) -> Result<()>
where
Self: Sized,
{
tracing_subscriber::fmt()
.with_env_filter(EnvFilter::from_default_env())
.with_target(false)
.with_file(true)
.with_line_number(true)
.without_time()
.compact()
.init();
color_eyre::install()?;

let input = Self::parse_input(format!(\"{}s/{}.txt\", type_of_input, Self::day()));

info!(\"Part 1: {}\", Self::part_1(&input));
info!(\"Part 2: {}\", Self::part_2(&input));

Ok(())
}

fn main() -> Result<()>
where
Self: Sized,
{
Self::run(\"input\")
}
\n

This 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\ninfo! and format string there.

\n

Now we can get to first of the nasty things we are going to do… And it is the\nday() 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
fn day() -> String {
let mut day = String::from(type_name::<Self>().split(\"::\").next().unwrap());
day.make_ascii_lowercase();

day.to_string()
}
\n
type_name

This feature is still experimental and considered to be internal, it is not\nadvised to use it any production code.

\n

And now we can get to the nastiest stuff 😩 We will generate the tests!

\n

We want to be able to generate tests for sample input in a following way:

\n
test_sample!(day_01, Day01, 42, 69);
\n

There's not much we can do, so we will write a macro to generate the tests for us.

\n
#[macro_export]
macro_rules! test_sample {
($mod_name:ident, $day_struct:tt, $part_1:expr, $part_2:expr) => {
#[cfg(test)]
mod $mod_name {
use super::*;

#[test]
fn test_part_1() {
let sample =
$day_struct::parse_input(&format!(\"samples/{}.txt\", $day_struct::day()));
assert_eq!($day_struct::part_1(&sample), $part_1);
}

#[test]
fn test_part_2() {
let sample =
$day_struct::parse_input(&format!(\"samples/{}.txt\", $day_struct::day()));
assert_eq!($day_struct::part_2(&sample), $part_2);
}
}
};
}
\n

We 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 “type” of the parameters for the macro. All\nparameters have their name prefixed with $ sign and you can define various “forms”\nof your macro. Let's go through it!

\n

We have following parameters:

\n
    \n
  • $mod_name which represents the name for the module with tests, it is typed\nwith 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\nwith tt which represents a token tree, in our case it is a type.
  • \n
  • $part_X represents the expected output for the Xth part and is of type expr\nwhich literally means an expression.
  • \n
\n

Apart 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
use aoc_2022::*;

type Input = String;
type Output = String;

struct DayXX;
impl Solution<Input, Output> for DayXX {
fn parse_input<P: AsRef<Path>>(pathname: P) -> Input {
file_to_string(pathname)
}

fn part_1(input: &Input) -> Output {
todo!()
}

fn part_2(input: &Input) -> Output {
todo!()
}
}

fn main() -> Result<()> {
// DayXX::run(\"sample\")
DayXX::main()
}

// test_sample!(day_XX, DayXX, , );
\n

Solution

\n

Not much to talk about, it is relatively easy to simulate.

\n

Day 10: Cathode-Ray Tube

\n
tl;dr

Emulating basic arithmetic operations on a CPU and drawing on CRT based on the\nCPU's accumulator.

\n

In 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

Problem is relatively simple and consists of simulating a CPU, I have approached\nit in a following way:

\n
fn evaluate_instructions(instructions: &[Instruction], mut out: Output) -> Output {
instructions
.iter()
.fold(State::new(), |state, instruction| {
state.execute(instruction, &mut out)
});

out
}
\n

We 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

You 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
tip

We could've seen something like this with the Result<T, E> type that can be\ndefined as

enum Result<T, E> {
Ok(T),
Err(E)
}
What does that mean though?

When 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:

match do_something(x) {
Ok(y) => {
println!(\"SUCCESS: {}\", y);
},
Err(y) => {
eprintln!(\"ERROR: {}\", y);
}
}
\n

My solution has a following outline:

\n
fn execute(&self, i: &Instruction, output: &mut Output) -> State {
// execute the instruction

// collect results if necessary
match output {
Output::Part1(x) => self.execute_part_1(y, x),
Output::Part2(x) => self.execute_part_2(y, x),
}

// return the obtained state
new_state
}
\n

You 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

The dirty and ingenious thing is that xs 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\nacross all iterations of fold.

\n
\n

Solution

\n

Similar to Day 9, but there are some technical details that can get you.

\n

Day 11: Monkey in the Middle

\n
tl;dr

Simulation of monkeys throwing stuff around and measuring your stress levels\nwhile your stuff is being passed around.

\n

I think I decided to use regular expressions here for the first time, cause\nparsing the input was a pain.

\n

Also I didn't expect to implement Euclidean algorithm in Rust…

\n

Solution

\n

Again, 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

Day 12: Hill Climbing Algorithm

\n
tl;dr

Finding shortest path up the hill and also shortest path down to the ground while\nalso rolling down the hill…

\n

As 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
fn bfs<F, G>(
graph: &[Vec<char>], start: &Position, has_edge: F, is_target: G
) -> Option<usize>
where
F: Fn(&[Vec<char>], &Position, &Position) -> bool,
G: Fn(&[Vec<char>], &Position) -> bool
\n

We 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

This was easy! And that is not very usual in Rust once you want to pass around\nfunctions. 👀

\n

Solution

\n

Looking for the shortest path… 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=1d = 1d=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

Day 13: Distress Signal

\n
tl;dr

Processing packets with structured data from the distress signal.

\n

You 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
impl Display for Packet {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Packet::Integer(x) => write!(f, \"{x}\"),
Packet::List(lst) => write!(f, \"[{}]\", lst.iter().map(|p| format!(\"{p}\")).join(\",\")),
}
}
}
\n

Solution

\n

A lot of technical details… Parsing is nasty too…

\n

Day 14: Regolith Reservoir

\n
tl;dr

Let's simulate falling sand grain-by-grain.

\n

Again, 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

Solution

\n

Tedious.

\n

Post Mortem

\n

Indexing

\n

I 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
note

I 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

It's relatively straightforward…

\n
impl<I, C> Index<Vector2D<I>> for [C]
where
I: Copy + TryInto<usize>,
<I as TryInto<usize>>::Error: Debug,
C: Index<usize>,
{
type Output = C::Output;

fn index(&self, index: Vector2D<I>) -> &Self::Output {
let (x, y): (usize, usize) =
(index.x.try_into().unwrap(), index.y.try_into().unwrap());
&self[y][x]
}
}

impl<I, C> IndexMut<Vector2D<I>> for [C]
where
I: Copy + TryInto<usize>,
<I as TryInto<usize>>::Error: Debug,
C: IndexMut<usize>,
{
fn index_mut(&mut self, index: Vector2D<I>) -> &mut Self::Output {
let (x, y): (usize, usize) =
(index.x.try_into().unwrap(), index.y.try_into().unwrap());
&mut self[y][x]
}
}
\n

We 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
note

I 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.

Also implementing TryFrom automatically provides you with a TryInto trait,\nsince it is relatively easy to implement. Just compare the following:

pub trait TryFrom<T>: Sized {
type Error;

fn try_from(value: T) -> Result<Self, Self::Error>;
}

pub trait TryInto<T>: Sized {
type Error;

fn try_into(self) -> Result<T, Self::Error>;
}
\n

OK, so we have our trait implemented, we should be able to use container[index],\nright? Yes… but actually no 😦

\n
error[E0277]: the type `[std::vec::Vec<i8>]` cannot be indexed by `aoc_2022::Vector2D<usize>`
--> src/bin/day08.rs:26:18
|
26 | if trees[pos] > tallest {
| ^^^ slice indices are of type `usize` or ranges of `usize`
|
= help: the trait `std::slice::SliceIndex<[std::vec::Vec<i8>]>` is not implemented for `aoc_2022::Vector2D<usize>`
= note: required for `std::vec::Vec<std::vec::Vec<i8>>` to implement `std::ops::Index<aoc_2022::Vector2D<usize>>`

error[E0277]: the type `[std::vec::Vec<i8>]` cannot be indexed by `aoc_2022::Vector2D<usize>`
--> src/bin/day08.rs:30:28
|
30 | max(tallest, trees[pos])
| ^^^ slice indices are of type `usize` or ranges of `usize`
|
= help: the trait `std::slice::SliceIndex<[std::vec::Vec<i8>]>` is not implemented for `aoc_2022::Vector2D<usize>`
= note: required for `std::vec::Vec<std::vec::Vec<i8>>` to implement `std::ops::Index<aoc_2022::Vector2D<usize>>`

error[E0277]: the type `[std::vec::Vec<i8>]` cannot be indexed by `aoc_2022::Vector2D<isize>`
--> src/bin/day08.rs:52:28
|
52 | let max_height = trees[position];
| ^^^^^^^^ slice indices are of type `usize` or ranges of `usize`
|
= help: the trait `std::slice::SliceIndex<[std::vec::Vec<i8>]>` is not implemented for `aoc_2022::Vector2D<isize>`
= note: required for `std::vec::Vec<std::vec::Vec<i8>>` to implement `std::ops::Index<aoc_2022::Vector2D<isize>>`
\n

Why? 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… we don't implement Index and IndexMut for\nthose. Just for the slices. 🤯 What are we going to do about it?

\n

We can either start copy-pasting or be smarter about it… 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

Implementing the macro can be done in a following way:

\n
macro_rules! generate_indices {
($container:ty) => {
impl<I, C> Index<Vector2D<I>> for $container
where
I: Copy + TryInto<usize>,
<I as TryInto<usize>>::Error: Debug,
C: Index<usize>,
{
type Output = C::Output;

fn index(&self, index: Vector2D<I>) -> &Self::Output {
let (x, y): (usize, usize) =
(index.x.try_into().unwrap(), index.y.try_into().unwrap());
&self[y][x]
}
}

impl<I, C> IndexMut<Vector2D<I>> for $container
where
I: Copy + TryInto<usize>,
<I as TryInto<usize>>::Error: Debug,
C: IndexMut<usize>,
{
fn index_mut(&mut self, index: Vector2D<I>) -> &mut Self::Output {
let (x, y): (usize, usize) =
(index.x.try_into().unwrap(), index.y.try_into().unwrap());
&mut self[y][x]
}
}
};
}
\n

And now we can simply do

\n
generate_indices!(VecDeque<C>);
generate_indices!([C]);
generate_indices!(Vec<C>);
// generate_indices!([C; N], const N: usize);
\n

The last type (I took the inspiration from the implementations of the Index and\nIndexMut 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
note

If I were to use 2D-indexing over [C; N] slices, I'd probably just go with the\ncopy-paste, cause the cost of this “monstrosity” outweighs the benefits of no DRY.

\n

Cause of the problem

\n

This 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
fn get_sum(nums: &Vec<i32>) -> i32 {
nums.iter().sum()
}

fn main() {
let nums = vec![1, 2, 3];
println!(\"Sum: {}\", get_sum(&nums));
}
\n

and you run clippy on it, you will get

\n
Checking playground v0.0.1 (/playground)
warning: writing `&Vec` instead of `&[_]` involves a new object where a slice will do
--> src/main.rs:1:18
|
1 | fn get_sum(nums: &Vec<i32>) -> i32 {
| ^^^^^^^^^ help: change this to: `&[i32]`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#ptr_arg
= note: `#[warn(clippy::ptr_arg)]` on by default

warning: `playground` (bin \"playground\") generated 1 warning
Finished dev [unoptimized + debuginfo] target(s) in 0.61s
\n

However, if you introduce a type alias, such as

\n
type Numbers = Vec<i32>;
\n

Then clippy won't say anything, cause there is literally nothing to suggest.\nHowever the outcome is not the same…

", "url": "https://blog.mfocko.xyz/blog/aoc-2022/2nd-week", "title": "2nd week of Advent of Code '22 in Rust", "summary": "Surviving second week in Rust.", @@ -93,7 +93,7 @@ }, { "id": "https://blog.mfocko.xyz/blog/aoc-2022/1st-week", - "content_html": "

Let's go through the first week of Advent of Code in Rust.

\n
note

If you wish to have a look at the solutions, you can follow them on my GitLab.\nMore specifically in the /src/bin/.

\n

I 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 👍 moments.

\n

Day 1: Calorie Counting

\n
tl;dr

As 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

Wakey wakey!

\n
\n

Programming 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

At first I've decided to put asserts into my main, something like

\n
assert_eq!(part_1(&sample), 24000);
info!(\"Part 1: {}\", part_1(&input));

assert_eq!(part_2(&sample), 45000);
info!(\"Part 2: {}\", part_2(&input));
\n

However, 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
#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_part_1() {
let sample = parse_input(\"samples/day01.txt\");
assert_eq!(part_1(&sample), 24000);
}

#[test]
fn test_part_2() {
let sample = parse_input(\"samples/day01.txt\");
assert_eq!(part_2(&sample), 45000);
}
}
\n

And 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

Also 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

Solution

\n

Well, 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

\n
tl;dr

You want to know what score did you achieve while playing Rock Paper Scissors.\nAnd then you want to be strategic about it.

\n

Apart from the technical details of the puzzle, it went relatively smooth.

\n

Solution

\n

I took relatively naïve approach and then tried to simplify it.

\n

Day 3: Rucksack Reorganization

\n
tl;dr

Let'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

This 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
Fun fact

Fighting the compiler took me 30 minutes.

\n

We 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
let top: HashSet<i32> = [1, 2, 3].iter().collect();
let bottom: HashSet<i32> = [3, 4, 5].iter().collect();
\n

Now, the first issue that we encounter is caused by the fact that we are using\na slice (the […]), 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
let top: HashSet<i32> = [1, 2, 3].into_iter().collect();
let bottom: HashSet<i32> = [3, 4, 5].into_iter().collect();
\n

This way the numbers will get copied instead of referenced. OK, let's find the\nintersection of those 2 collections:

\n
println!(\"Common elements: {:?}\", top.intersection(&bottom));
\n
Common elements: [3]
\n
caution

Notice that we need to do &bottom. It explicitly specifies that .intersection\nborrows the bottom, i.e. takes an immutable reference to it.

\n

That's what we want, right? Looks like it! \\o/

\n

Next 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

Let's have a look at the type of the .intersection

\n
pub fn intersection<'a>(
    &'a self,
    other: &'a HashSet<T, S>
) -> Intersection<'a, T, S>
\n

OK… Huh… But we have an example there!

\n
let intersection: HashSet<_> = a.intersection(&b).collect();
\n

Cool, that's all we need.

\n
let top: HashSet<i32> = [1, 2, 3, 4].into_iter().collect();
let bottom: HashSet<i32> = [3, 4, 5, 6].into_iter().collect();
let top_2: HashSet<i32> = [2, 3, 4, 5, 6].into_iter().collect();
let bottom_2: HashSet<i32> = [4, 5, 6].into_iter().collect();

let intersection: HashSet<_> = top.intersection(&bottom).collect();
println!(\"Intersection: {:?}\", intersection);
\n
Intersection: {3, 4}
\n

Cool, so let's do the intersection with the top_2:

\n
let top: HashSet<i32> = [1, 2, 3, 4].into_iter().collect();
let bottom: HashSet<i32> = [3, 4, 5, 6].into_iter().collect();
let top_2: HashSet<i32> = [2, 3, 4, 5, 6].into_iter().collect();
let bottom_2: HashSet<i32> = [4, 5, 6].into_iter().collect();

let intersection: HashSet<_> = top.intersection(&bottom).collect();
let intersection: HashSet<_> = intersection.intersection(&top_2).collect();
println!(\"Intersection: {:?}\", intersection);
\n

And we get yelled at by the compiler:

\n
error[E0308]: mismatched types
--> src/main.rs:10:58
|
10 | let intersection: HashSet<_> = intersection.intersection(&top_2).collect();
| ------------ ^^^^^^ expected `&i32`, found `i32`
| |
| arguments to this function are incorrect
|
= note: expected reference `&HashSet<&i32>`
found reference `&HashSet<i32>`
\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
tip

It may seem as a very weird decision, but in fact it makes some sense… It allows\nyou to do intersection of items that may not be possible to copy. Overall this is\na “tax” 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\nbehavior.

\n

To resolve this we need to get an iterator that clones the elements:

\n
let top: HashSet<i32> = [1, 2, 3, 4].into_iter().collect();
let bottom: HashSet<i32> = [3, 4, 5, 6].into_iter().collect();
let top_2: HashSet<i32> = [2, 3, 4, 5, 6].into_iter().collect();
let bottom_2: HashSet<i32> = [4, 5, 6].into_iter().collect();

let intersection: HashSet<_> = top.intersection(&bottom).cloned().collect();
let intersection: HashSet<_> = intersection.intersection(&top_2).cloned().collect();
let intersection: HashSet<_> = intersection.intersection(&bottom_2).cloned().collect();
println!(\"Intersection: {:?}\", intersection);
\n
Intersection: {4}
\n

Solution

\n

The approach is pretty simple, if you omit the 1on1 with the compiler. You just\nhave some fun with the set operations :)

\n

Day 4: Camp Cleanup

\n
tl;dr

Elves are cleaning up the camp and they got overlapping sections to clean up.\nFind how many overlap and can take the day off.

\n

RangeInclusive is your friend not an enemy :)

\n

Solution

\n

Relatively easy, you just need to parse the input and know what you want. Rust's\nRangeInclusive type helped a lot, cause it took care of all abstractions.

\n

Day 5: Supply Stacks

\n
tl;dr

Let's play with stacks of crates.

\n

Very easy problem with very annoying input. You can judge yourself:

\n
    [D]    
[N] [C]
[Z] [M] [P]
1 2 3

move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2
\n

Good luck transforming that into something reasonable :)

\n
Fun fact

Took me 40 minutes to parse this reasonably, including fighting the compiler.

\n

Solution

\n

For the initial solution I went with a manual solution (as in I have done all\nthe work. Later on I have decided to explore the std and interface of the\nstd::vec::Vec and found split_off which takes an index and splits (duh)\nthe vector:

\n
let mut vec = vec![1, 2, 3];
let vec2 = vec.split_off(1);
assert_eq!(vec, [1]);
assert_eq!(vec2, [2, 3]);
\n

This helped me simplify my solution a lot and also get rid of some edge cases.

\n

Day 6: Tuning Trouble

\n
tl;dr

Finding start of the message in a very weird protocol. Start of the message is\ndenoted by NNN unique consecutive characters.

\n

Solution

\n

A 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

One 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

Other 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

Day 7: No Space Left On Device

\n
tl;dr

Let'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

I was waiting for this moment, and yet it got me!\nimagine me swearing for hours

\n
\n

Solution

\n

We need to “build” a file system from the input that is given in a following form:

\n
$ cd /
$ ls
dir a
14848514 b.txt
8504156 c.dat
dir d
$ cd a
$ ls
dir e
29116 f
2557 g
62596 h.lst
$ cd e
$ ls
584 i
$ cd ..
$ cd ..
$ cd d
$ ls
4060174 j
8033020 d.log
5626152 d.ext
7214296 k
\n

There are few ways in which you can achieve this and also you can assume some\npreconditions, but why would we do that, right? :)

\n

You can “slap” this in either HashMap or BTreeMap and call it a day.\nAnd that would be boring…

\n
tip

BTreeMap is quite fitting for this, don't you think?

\n

I 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…

\n

Then I looked up some implementations of trees or linked lists and decided to try\nRc<Cell<T>>. And I got my ass whopped by the compiler once again. /o\\

\n
tip

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++.

Rc<T> represents a dynamically allocated memory on heap. On top of that it is\nreference counted (that's what the Rc stands for). You can imagine this as\nstd::shared_ptr<T> in C++.

Now the fun stuff. Neither of them lets you mutate the contents of the memory.

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.

RefCell<T> is similar to the Cell<T>, but the borrowing rules (how many mutable\nreferences are present) are checked dynamically.

So in the end, if you want something like std::shared_ptr<T> in Rust, you want\nto have Rc<RefCell<T>>.

\n

So, 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 😩

\n
type FileHandle = Rc<RefCell<AocFile>>;

#[derive(Debug)]
enum AocFile {
File(usize),
Directory(BTreeMap<String, FileHandle>),
}
\n

Let'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

Now to the fun part! AocFile value can be represented in two ways:

\n
    \n
  • File(usize), e.g. AocFile::File(123) and we can pattern match it, if we\nneed to
  • \n
  • Directory(BTreeMap<String, FileHandle>) will represent the directory and will\ncontain map matching the name of the files (or directories) within to their\nrespective file handles
  • \n
\n

I 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

We 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

I have chosen to implement tree catamorphism 😩. 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

Another 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

One 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

Post Mortem

\n

Things that have been brought up in the discussion later on.

\n

Rc<T> vs Rc<RefCell<T>>

\n

It 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\nRc<RefCell<T>>
  • \n
\n

Now, in Rust it is a bit more complicated, because the type that represents the\n“shared pointer” is Rc<T>. What RefCell<T> does is making sure that there is\nonly one “owner” of a mutable reference at a time (and dynamically, as opposed\nto the Cell<T>).

\n

Therefore 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
\n

You 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>)

", + "content_html": "

Let's go through the first week of Advent of Code in Rust.

\n
note

If you wish to have a look at the solutions, you can follow them on my GitLab.\nMore specifically in the /src/bin/.

\n

I 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 👍 moments.

\n

Day 1: Calorie Counting

\n
tl;dr

As 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

Wakey wakey!

\n
\n

Programming 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

At first I've decided to put asserts into my main, something like

\n
assert_eq!(part_1(&sample), 24000);
info!(\"Part 1: {}\", part_1(&input));

assert_eq!(part_2(&sample), 45000);
info!(\"Part 2: {}\", part_2(&input));
\n

However, 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
#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_part_1() {
let sample = parse_input(\"samples/day01.txt\");
assert_eq!(part_1(&sample), 24000);
}

#[test]
fn test_part_2() {
let sample = parse_input(\"samples/day01.txt\");
assert_eq!(part_2(&sample), 45000);
}
}
\n

And 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

Also 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

Solution

\n

Well, 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

\n
tl;dr

You want to know what score did you achieve while playing Rock Paper Scissors.\nAnd then you want to be strategic about it.

\n

Apart from the technical details of the puzzle, it went relatively smooth.

\n

Solution

\n

I took relatively naïve approach and then tried to simplify it.

\n

Day 3: Rucksack Reorganization

\n
tl;dr

Let'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

This 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
Fun fact

Fighting the compiler took me 30 minutes.

\n

We 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
let top: HashSet<i32> = [1, 2, 3].iter().collect();
let bottom: HashSet<i32> = [3, 4, 5].iter().collect();
\n

Now, the first issue that we encounter is caused by the fact that we are using\na slice (the […]), 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
let top: HashSet<i32> = [1, 2, 3].into_iter().collect();
let bottom: HashSet<i32> = [3, 4, 5].into_iter().collect();
\n

This way the numbers will get copied instead of referenced. OK, let's find the\nintersection of those 2 collections:

\n
println!(\"Common elements: {:?}\", top.intersection(&bottom));
\n
Common elements: [3]
\n
caution

Notice that we need to do &bottom. It explicitly specifies that .intersection\nborrows the bottom, i.e. takes an immutable reference to it.

\n

That's what we want, right? Looks like it! \\o/

\n

Next 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

Let's have a look at the type of the .intersection

\n
pub fn intersection<'a>(
    &'a self,
    other: &'a HashSet<T, S>
) -> Intersection<'a, T, S>
\n

OK… Huh… But we have an example there!

\n
let intersection: HashSet<_> = a.intersection(&b).collect();
\n

Cool, that's all we need.

\n
let top: HashSet<i32> = [1, 2, 3, 4].into_iter().collect();
let bottom: HashSet<i32> = [3, 4, 5, 6].into_iter().collect();
let top_2: HashSet<i32> = [2, 3, 4, 5, 6].into_iter().collect();
let bottom_2: HashSet<i32> = [4, 5, 6].into_iter().collect();

let intersection: HashSet<_> = top.intersection(&bottom).collect();
println!(\"Intersection: {:?}\", intersection);
\n
Intersection: {3, 4}
\n

Cool, so let's do the intersection with the top_2:

\n
let top: HashSet<i32> = [1, 2, 3, 4].into_iter().collect();
let bottom: HashSet<i32> = [3, 4, 5, 6].into_iter().collect();
let top_2: HashSet<i32> = [2, 3, 4, 5, 6].into_iter().collect();
let bottom_2: HashSet<i32> = [4, 5, 6].into_iter().collect();

let intersection: HashSet<_> = top.intersection(&bottom).collect();
let intersection: HashSet<_> = intersection.intersection(&top_2).collect();
println!(\"Intersection: {:?}\", intersection);
\n

And we get yelled at by the compiler:

\n
error[E0308]: mismatched types
--> src/main.rs:10:58
|
10 | let intersection: HashSet<_> = intersection.intersection(&top_2).collect();
| ------------ ^^^^^^ expected `&i32`, found `i32`
| |
| arguments to this function are incorrect
|
= note: expected reference `&HashSet<&i32>`
found reference `&HashSet<i32>`
\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
tip

It may seem as a very weird decision, but in fact it makes some sense… It allows\nyou to do intersection of items that may not be possible to copy. Overall this is\na “tax” 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\nbehavior.

\n

To resolve this we need to get an iterator that clones the elements:

\n
let top: HashSet<i32> = [1, 2, 3, 4].into_iter().collect();
let bottom: HashSet<i32> = [3, 4, 5, 6].into_iter().collect();
let top_2: HashSet<i32> = [2, 3, 4, 5, 6].into_iter().collect();
let bottom_2: HashSet<i32> = [4, 5, 6].into_iter().collect();

let intersection: HashSet<_> = top.intersection(&bottom).cloned().collect();
let intersection: HashSet<_> = intersection.intersection(&top_2).cloned().collect();
let intersection: HashSet<_> = intersection.intersection(&bottom_2).cloned().collect();
println!(\"Intersection: {:?}\", intersection);
\n
Intersection: {4}
\n

Solution

\n

The approach is pretty simple, if you omit the 1on1 with the compiler. You just\nhave some fun with the set operations :)

\n

Day 4: Camp Cleanup

\n
tl;dr

Elves are cleaning up the camp and they got overlapping sections to clean up.\nFind how many overlap and can take the day off.

\n

RangeInclusive is your friend not an enemy :)

\n

Solution

\n

Relatively easy, you just need to parse the input and know what you want. Rust's\nRangeInclusive type helped a lot, cause it took care of all abstractions.

\n

Day 5: Supply Stacks

\n
tl;dr

Let's play with stacks of crates.

\n

Very easy problem with very annoying input. You can judge yourself:

\n
    [D]
[N] [C]
[Z] [M] [P]
1 2 3

move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2
\n

Good luck transforming that into something reasonable :)

\n
Fun fact

Took me 40 minutes to parse this reasonably, including fighting the compiler.

\n

Solution

\n

For the initial solution I went with a manual solution (as in I have done all\nthe work. Later on I have decided to explore the std and interface of the\nstd::vec::Vec and found split_off which takes an index and splits (duh)\nthe vector:

\n
let mut vec = vec![1, 2, 3];
let vec2 = vec.split_off(1);
assert_eq!(vec, [1]);
assert_eq!(vec2, [2, 3]);
\n

This helped me simplify my solution a lot and also get rid of some edge cases.

\n

Day 6: Tuning Trouble

\n
tl;dr

Finding start of the message in a very weird protocol. Start of the message is\ndenoted by NNN unique consecutive characters.

\n

Solution

\n

A 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

One 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

Other 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

Day 7: No Space Left On Device

\n
tl;dr

Let'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

I was waiting for this moment, and yet it got me!\nimagine me swearing for hours

\n
\n

Solution

\n

We need to “build” a file system from the input that is given in a following form:

\n
$ cd /
$ ls
dir a
14848514 b.txt
8504156 c.dat
dir d
$ cd a
$ ls
dir e
29116 f
2557 g
62596 h.lst
$ cd e
$ ls
584 i
$ cd ..
$ cd ..
$ cd d
$ ls
4060174 j
8033020 d.log
5626152 d.ext
7214296 k
\n

There are few ways in which you can achieve this and also you can assume some\npreconditions, but why would we do that, right? :)

\n

You can “slap” this in either HashMap or BTreeMap and call it a day.\nAnd that would be boring…

\n
tip

BTreeMap is quite fitting for this, don't you think?

\n

I 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…

\n

Then I looked up some implementations of trees or linked lists and decided to try\nRc<Cell<T>>. And I got my ass whopped by the compiler once again. /o\\

\n
tip

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++.

Rc<T> represents a dynamically allocated memory on heap. On top of that it is\nreference counted (that's what the Rc stands for). You can imagine this as\nstd::shared_ptr<T> in C++.

Now the fun stuff. Neither of them lets you mutate the contents of the memory.

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.

RefCell<T> is similar to the Cell<T>, but the borrowing rules (how many mutable\nreferences are present) are checked dynamically.

So in the end, if you want something like std::shared_ptr<T> in Rust, you want\nto have Rc<RefCell<T>>.

\n

So, 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 😩

\n
type FileHandle = Rc<RefCell<AocFile>>;

#[derive(Debug)]
enum AocFile {
File(usize),
Directory(BTreeMap<String, FileHandle>),
}
\n

Let'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

Now to the fun part! AocFile value can be represented in two ways:

\n
    \n
  • File(usize), e.g. AocFile::File(123) and we can pattern match it, if we\nneed to
  • \n
  • Directory(BTreeMap<String, FileHandle>) will represent the directory and will\ncontain map matching the name of the files (or directories) within to their\nrespective file handles
  • \n
\n

I 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

We 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

I have chosen to implement tree catamorphism 😩. 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

Another 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

One 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

Post Mortem

\n

Things that have been brought up in the discussion later on.

\n

Rc<T> vs Rc<RefCell<T>>

\n

It 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\nRc<RefCell<T>>
  • \n
\n

Now, in Rust it is a bit more complicated, because the type that represents the\n“shared pointer” is Rc<T>. What RefCell<T> does is making sure that there is\nonly one “owner” of a mutable reference at a time (and dynamically, as opposed\nto the Cell<T>).

\n

Therefore 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
\n

You 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>)

", "url": "https://blog.mfocko.xyz/blog/aoc-2022/1st-week", "title": "1st week of Advent of Code '22 in Rust", "summary": "Surviving first week in Rust.", diff --git a/blog/index.html b/blog/index.html index 753fdb1..dfe66c3 100644 --- a/blog/index.html +++ b/blog/index.html @@ -14,7 +14,7 @@ - + diff --git a/blog/leetcode/sort-diagonally/index.html b/blog/leetcode/sort-diagonally/index.html index 13a3ce0..f09be2c 100644 --- a/blog/leetcode/sort-diagonally/index.html +++ b/blog/leetcode/sort-diagonally/index.html @@ -14,7 +14,7 @@ - + @@ -35,7 +35,7 @@ order and return the resulting matrix.

Image describing the problem

Skeleton and initial adjustments

We are given the following skeleton for the C++ and the given challenge:

-
class Solution {
public:
vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {

}
};
+
class Solution {
public:
vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {

}
};

The task is to sort the passed matrix diagonally and then return it. First of all, I don't like to solve this in a web browser, so we'll need to adjust it accordingly for running it locally. We'll start by including the vector header and using diff --git a/blog/rss.xml b/blog/rss.xml index a92a327..8d68eb4 100644 --- a/blog/rss.xml +++ b/blog/rss.xml @@ -314,7 +314,7 @@ everything:

You can also see that it simplifies the meaning a bit and it is more explicit than the previous versions.

And for the tests:

-
     #[test]
fn test_from() {
- for (n, s) in EXAMPLES.iter() {
- assert_eq!(from_snafu(s), *n);
+ for (&n, s) in EXAMPLES.iter() {
+ assert_eq!(s.parse::<SNAFU>().unwrap().value, n);
}
}

#[test]
fn test_to() {
- for (n, s) in EXAMPLES.iter() {
- assert_eq!(to_snafu(*n), s.to_string());
+ for (&n, s) in EXAMPLES.iter() {
+ assert_eq!(SNAFU::from(n).to_string(), s.to_string());
}
+
     #[test]
fn test_from() {
- for (n, s) in EXAMPLES.iter() {
- assert_eq!(from_snafu(s), *n);
+ for (&n, s) in EXAMPLES.iter() {
+ assert_eq!(s.parse::<SNAFU>().unwrap().value, n);
}
}

#[test]
fn test_to() {
- for (n, s) in EXAMPLES.iter() {
- assert_eq!(to_snafu(*n), s.to_string());
+ for (&n, s) in EXAMPLES.iter() {
+ assert_eq!(SNAFU::from(n).to_string(), s.to_string());
}

Summary

Let's wrap the whole thing up! Keeping in mind both AoC and the Rust…

Finished advent calendar :smile:

@@ -580,7 +580,7 @@ order and return the resulting matrix.

Image describing the problem

Skeleton and initial adjustments

We are given the following skeleton for the C++ and the given challenge:

-
class Solution {
public:
vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {

}
};
+
class Solution {
public:
vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {

}
};

The task is to sort the passed matrix diagonally and then return it. First of all, I don't like to solve this in a web browser, so we'll need to adjust it accordingly for running it locally. We'll start by including the vector header and using @@ -1063,7 +1063,7 @@ right? Yes… but actually no 😦

the fun part consists of the fact that in other place, where we were using it, we were passing the &[Vec<T>], but this is coming from a helper functions that take &Vec<Vec<T>> instead. And… we don't implement Index and IndexMut for -those. Just for the slices. 🤯 What are we going to do about it?

+those. Just for the slices. 🤯 What are we going to do about it?

We can either start copy-pasting or be smarter about it… I choose to be smarter, so let's implement a macro! The only difference across the implementations are the types of the outer containers. Implementation doesn't differ at all!

@@ -1198,7 +1198,7 @@ Find how many overlap and can take the day off.

Day 5: Supply Stacks

tl;dr

Let's play with stacks of crates.

Very easy problem with very annoying input. You can judge yourself:

-
    [D]    
[N] [C]
[Z] [M] [P]
1 2 3

move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2
+
    [D]
[N] [C]
[Z] [M] [P]
1 2 3

move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2

Good luck transforming that into something reasonable :)

Fun fact

Took me 40 minutes to parse this reasonably, including fighting the compiler.

Solution

diff --git a/blog/tags/admin/index.html b/blog/tags/admin/index.html index 4eef209..5a344e8 100644 --- a/blog/tags/admin/index.html +++ b/blog/tags/admin/index.html @@ -14,7 +14,7 @@ - + diff --git a/blog/tags/advent-of-code-2022/index.html b/blog/tags/advent-of-code-2022/index.html index e718542..3621bac 100644 --- a/blog/tags/advent-of-code-2022/index.html +++ b/blog/tags/advent-of-code-2022/index.html @@ -14,7 +14,7 @@ - + diff --git a/blog/tags/advent-of-code/index.html b/blog/tags/advent-of-code/index.html index 0454069..794e115 100644 --- a/blog/tags/advent-of-code/index.html +++ b/blog/tags/advent-of-code/index.html @@ -14,7 +14,7 @@ - + diff --git a/blog/tags/copr/index.html b/blog/tags/copr/index.html index 039fd1c..d11b0e0 100644 --- a/blog/tags/copr/index.html +++ b/blog/tags/copr/index.html @@ -14,7 +14,7 @@ - + diff --git a/blog/tags/cpp/index.html b/blog/tags/cpp/index.html index 961f352..e8685b0 100644 --- a/blog/tags/cpp/index.html +++ b/blog/tags/cpp/index.html @@ -14,7 +14,7 @@ - + diff --git a/blog/tags/index.html b/blog/tags/index.html index f2ed7aa..02f30a7 100644 --- a/blog/tags/index.html +++ b/blog/tags/index.html @@ -14,7 +14,7 @@ - + diff --git a/blog/tags/iterators/index.html b/blog/tags/iterators/index.html index 4d1aa6f..202adbb 100644 --- a/blog/tags/iterators/index.html +++ b/blog/tags/iterators/index.html @@ -14,7 +14,7 @@ - + diff --git a/blog/tags/leetcode/index.html b/blog/tags/leetcode/index.html index c8fc62b..58c1271 100644 --- a/blog/tags/leetcode/index.html +++ b/blog/tags/leetcode/index.html @@ -14,7 +14,7 @@ - + diff --git a/blog/tags/red-hat/index.html b/blog/tags/red-hat/index.html index a985354..bfe1d55 100644 --- a/blog/tags/red-hat/index.html +++ b/blog/tags/red-hat/index.html @@ -14,7 +14,7 @@ - + diff --git a/blog/tags/rust/index.html b/blog/tags/rust/index.html index 2a171c4..00b7a7f 100644 --- a/blog/tags/rust/index.html +++ b/blog/tags/rust/index.html @@ -14,7 +14,7 @@ - + diff --git a/blog/tags/vps/index.html b/blog/tags/vps/index.html index 9000f9d..96081ae 100644 --- a/blog/tags/vps/index.html +++ b/blog/tags/vps/index.html @@ -14,7 +14,7 @@ - + diff --git a/blog/tags/🏭/index.html b/blog/tags/🏭/index.html index a7e01ad..549ae2d 100644 --- a/blog/tags/🏭/index.html +++ b/blog/tags/🏭/index.html @@ -14,7 +14,7 @@ - + diff --git a/c/bonuses/seminar-03/index.html b/c/bonuses/seminar-03/index.html index 2ed7fb6..468147a 100644 --- a/c/bonuses/seminar-03/index.html +++ b/c/bonuses/seminar-03/index.html @@ -16,7 +16,7 @@ - + diff --git a/c/bonuses/seminar-04/index.html b/c/bonuses/seminar-04/index.html index 955abc3..2817c68 100644 --- a/c/bonuses/seminar-04/index.html +++ b/c/bonuses/seminar-04/index.html @@ -16,7 +16,7 @@ - + diff --git a/c/bonuses/seminar-05-06/index.html b/c/bonuses/seminar-05-06/index.html index fdc57c2..6714682 100644 --- a/c/bonuses/seminar-05-06/index.html +++ b/c/bonuses/seminar-05-06/index.html @@ -16,7 +16,7 @@ - + @@ -114,6 +114,6 @@ which is encrypted character H using this method.

For decrypting, reverse the steps.

Submitting

In case you have any questions, feel free to reach out to me.

-
+
\ No newline at end of file diff --git a/c/bonuses/seminar-08/index.html b/c/bonuses/seminar-08/index.html index dd349a2..a362465 100644 --- a/c/bonuses/seminar-08/index.html +++ b/c/bonuses/seminar-08/index.html @@ -16,7 +16,7 @@ - + @@ -94,6 +94,6 @@ Implementation and format of the pretty-print is totally up to you. :)

Submitting

In case you have any questions, feel free to reach out to me.

-
+
\ No newline at end of file diff --git a/c/bonuses/seminar-10/index.html b/c/bonuses/seminar-10/index.html index e203f01..9fecb92 100644 --- a/c/bonuses/seminar-10/index.html +++ b/c/bonuses/seminar-10/index.html @@ -16,7 +16,7 @@ - + @@ -136,6 +136,6 @@ it is a not requirement at all and you can still get all points for the bonus ;)

Submitting

In case you have any questions, feel free to reach out to me.

-
+
\ No newline at end of file diff --git a/c/category/bonuses/index.html b/c/category/bonuses/index.html index f8046c9..559aeb1 100644 --- a/c/category/bonuses/index.html +++ b/c/category/bonuses/index.html @@ -16,7 +16,7 @@ - + diff --git a/c/category/practice-exams/index.html b/c/category/practice-exams/index.html index c59b9d3..f43944b 100644 --- a/c/category/practice-exams/index.html +++ b/c/category/practice-exams/index.html @@ -16,7 +16,7 @@ - + diff --git a/c/index.html b/c/index.html index 35b3121..7543212 100644 --- a/c/index.html +++ b/c/index.html @@ -14,10 +14,10 @@ - + - + \ No newline at end of file diff --git a/c/mr/index.html b/c/mr/index.html index 742ba1a..ff467c6 100644 --- a/c/mr/index.html +++ b/c/mr/index.html @@ -14,7 +14,7 @@ - + @@ -87,6 +87,6 @@ For the sake of safety, do not continue without clean repository. Then with comm be main or trunk.

aisa$ git status
# Check if repository is clean

# If you know, what is your default branch, you can skip next command.
aisa$ git branch
# Find the default branch in the list; should be one of the `master`, `main` or
# `trunk` and you should not have more than one of those.
# In case the list clears the terminal and you cannot see shell prompt, you can
# press `q` to quit the pager.

aisa$ git checkout master

-

Adapted from: https://www.fi.muni.cz/~xlacko1/pb071/mr.html

+

Adapted from: https://www.fi.muni.cz/~xlacko1/pb071/mr.html

\ No newline at end of file diff --git a/c/pexam/cams/index.html b/c/pexam/cams/index.html index 40fd00a..75421cf 100644 --- a/c/pexam/cams/index.html +++ b/c/pexam/cams/index.html @@ -16,7 +16,7 @@ - + diff --git a/c/pexam/garbage_collect/index.html b/c/pexam/garbage_collect/index.html index 7b8dc78..7e3a277 100644 --- a/c/pexam/garbage_collect/index.html +++ b/c/pexam/garbage_collect/index.html @@ -16,7 +16,7 @@ - + diff --git a/contributions/index.html b/contributions/index.html index fb40e90..7d39896 100644 --- a/contributions/index.html +++ b/contributions/index.html @@ -14,10 +14,10 @@ - + -

Contributions

Many of my contributions to open-source projects.

tmt

Description

The `tmt` tool provides a user-friendly way to work with tests. You can comfortably create new tests, safely and easily run tests across different environments, review test results, debug test code and enable tests in the CI using a consistent and concise config.

Contribution

Just a smallish contribution to the docs related to the changes implemented on the Packit side.

Fedora Infrastructure Ansible

Description

Collection of Ansible playbooks that powers the Fedora Infrastructure.

Contribution

I have adjusted the groups in the Bodhi playbooks after Packit has been granted the privileges to propose updates without restrictions.

Bodhi

Description

Bodhi is a web-system that facilitates the process of publishing updates for a Fedora-based software distribution.

Contribution

I have adjusted the client, so that it doesn't show secrets in terminal when you log in to the Bodhi via browser.

Gluetool Modules Collection

Description

Modules for gluetool — a command line centric framework usable for glueing modules into a pipeline.

Contribution
  • I have proposed a possible implementation of git merging that was later on extended.
  • I have tried to help out with Copr module after they deprecated older version of their API.

Pagure

Description

Pagure is a git-centered forge, python based using pygit2.

Contribution

I have added an API endpoint for reopening pull requests.

Copr

Description

RPM build system - upstream for Copr.

Contribution
  • Supporting external repositories for custom SRPM build method.
  • Allowing admins of Copr repositories to build without the need to ask for explicit builder permissions.

python-gitlab

Description

A python wrapper for the GitLab API.

Contribution

I have contributed support for the merge_ref on merge requests that hasn't been supported, yet it was present in the GitLab API.

PatternFly React

Description

A set of React components for the PatternFly project.

Contribution

When working on Packit Dashboard, I have spotted smaller bugs that were present in this project and fixed them upstream to provide better experience for our users.

Fira Code

Description

Free monospaced font with programming ligatures.

Contribution

I have set up a GitHub Action for building the font on each push to the default branch allowing users to install bleeding edge version of the font.

nixpkgs

Description

Nixpkgs is a collection of over 80,000 software packages that can be installed with the Nix package manager. It also implements NixOS, a purely-functional Linux distribution.

Contribution

When I was trying out the nixpkgs, I have tried to bump .NET Core to the latest version. My changes haven't been accepted as they required bumping of multiple more packages that depended upon the .NET Core.

Darcula

Description

A theme for Visual Studio Code based on Darcula theme from Jetbrains IDEs.

Contribution

I have contributed support for diff files, though the project doesn't seem to be live anymore, so it hasn't been accepted as of now.

Packit

Description

An open source project aiming to ease the integration of your project with Fedora Linux, CentOS Stream and other distributions.

Contribution

Have a look at my pull requests.

Snitch

Description

Language agnostic tool that collects TODOs in the source code and reports them as Issues.

Contribution
  • Environment variable support for self-hosted GitLab instances
  • GitLab support

Karel the Robot

Description

Karel the robot is in general an educational programming language for beginners, created by Richard E. Pattis. This is implementation of Karel the Robot for C programming language.

This project is used for educational purposes at TUKE.

Contribution

I have contributed some refactoring tips to the author of the library.

+

Contributions

Many of my contributions to open-source projects.

tmt

Description

The `tmt` tool provides a user-friendly way to work with tests. You can comfortably create new tests, safely and easily run tests across different environments, review test results, debug test code and enable tests in the CI using a consistent and concise config.

Contribution

Just a smallish contribution to the docs related to the changes implemented on the Packit side.

Fedora Infrastructure Ansible

Description

Collection of Ansible playbooks that powers the Fedora Infrastructure.

Contribution

I have adjusted the groups in the Bodhi playbooks after Packit has been granted the privileges to propose updates without restrictions.

Bodhi

Description

Bodhi is a web-system that facilitates the process of publishing updates for a Fedora-based software distribution.

Contribution

I have adjusted the client, so that it doesn't show secrets in terminal when you log in to the Bodhi via browser.

Gluetool Modules Collection

Description

Modules for gluetool — a command line centric framework usable for glueing modules into a pipeline.

Contribution
  • I have proposed a possible implementation of git merging that was later on extended.
  • I have tried to help out with Copr module after they deprecated older version of their API.

Pagure

Description

Pagure is a git-centered forge, python based using pygit2.

Contribution

I have added an API endpoint for reopening pull requests.

Copr

Description

RPM build system - upstream for Copr.

Contribution
  • Supporting external repositories for custom SRPM build method.
  • Allowing admins of Copr repositories to build without the need to ask for explicit builder permissions.

python-gitlab

Description

A python wrapper for the GitLab API.

Contribution

I have contributed support for the merge_ref on merge requests that hasn't been supported, yet it was present in the GitLab API.

PatternFly React

Description

A set of React components for the PatternFly project.

Contribution

When working on Packit Dashboard, I have spotted smaller bugs that were present in this project and fixed them upstream to provide better experience for our users.

Fira Code

Description

Free monospaced font with programming ligatures.

Contribution

I have set up a GitHub Action for building the font on each push to the default branch allowing users to install bleeding edge version of the font.

nixpkgs

Description

Nixpkgs is a collection of over 80,000 software packages that can be installed with the Nix package manager. It also implements NixOS, a purely-functional Linux distribution.

Contribution

When I was trying out the nixpkgs, I have tried to bump .NET Core to the latest version. My changes haven't been accepted as they required bumping of multiple more packages that depended upon the .NET Core.

Darcula

Description

A theme for Visual Studio Code based on Darcula theme from Jetbrains IDEs.

Contribution

I have contributed support for diff files, though the project doesn't seem to be live anymore, so it hasn't been accepted as of now.

Packit

Description

An open source project aiming to ease the integration of your project with Fedora Linux, CentOS Stream and other distributions.

Contribution

Have a look at my pull requests.

Snitch

Description

Language agnostic tool that collects TODOs in the source code and reports them as Issues.

Contribution
  • Environment variable support for self-hosted GitLab instances
  • GitLab support

Karel the Robot

Description

Karel the robot is in general an educational programming language for beginners, created by Richard E. Pattis. This is implementation of Karel the Robot for C programming language.

This project is used for educational purposes at TUKE.

Contribution

I have contributed some refactoring tips to the author of the library.

\ No newline at end of file diff --git a/cpp/category/exceptions-and-raii/index.html b/cpp/category/exceptions-and-raii/index.html index 0326e95..1811abf 100644 --- a/cpp/category/exceptions-and-raii/index.html +++ b/cpp/category/exceptions-and-raii/index.html @@ -16,7 +16,7 @@ - + diff --git a/cpp/environment/index.html b/cpp/environment/index.html index 7e5e55f..875a45a 100644 --- a/cpp/environment/index.html +++ b/cpp/environment/index.html @@ -16,7 +16,7 @@ - + diff --git a/cpp/exceptions-and-raii/placeholders/index.html b/cpp/exceptions-and-raii/placeholders/index.html index 48884d3..45f494f 100644 --- a/cpp/exceptions-and-raii/placeholders/index.html +++ b/cpp/exceptions-and-raii/placeholders/index.html @@ -16,7 +16,7 @@ - + diff --git a/cpp/index.html b/cpp/index.html index 9b54458..f5ff420 100644 --- a/cpp/index.html +++ b/cpp/index.html @@ -14,10 +14,10 @@ - + - + \ No newline at end of file diff --git a/files/algorithms/graphs/iterative-and-iterators.tar.bz2 b/files/algorithms/graphs/iterative-and-iterators.tar.bz2 index d6321c0..a3b5098 100644 Binary files a/files/algorithms/graphs/iterative-and-iterators.tar.bz2 and b/files/algorithms/graphs/iterative-and-iterators.tar.bz2 differ diff --git a/files/algorithms/graphs/iterative-and-iterators.tar.gz b/files/algorithms/graphs/iterative-and-iterators.tar.gz index 86bc85a..aa52875 100644 Binary files a/files/algorithms/graphs/iterative-and-iterators.tar.gz and b/files/algorithms/graphs/iterative-and-iterators.tar.gz differ diff --git a/files/algorithms/paths/bf-to-astar.tar.bz2 b/files/algorithms/paths/bf-to-astar.tar.bz2 index 9a279e9..d65e415 100644 Binary files a/files/algorithms/paths/bf-to-astar.tar.bz2 and b/files/algorithms/paths/bf-to-astar.tar.bz2 differ diff --git a/files/algorithms/paths/bf-to-astar.tar.gz b/files/algorithms/paths/bf-to-astar.tar.gz index 2ebec3e..7f5eb46 100644 Binary files a/files/algorithms/paths/bf-to-astar.tar.gz and b/files/algorithms/paths/bf-to-astar.tar.gz differ diff --git a/files/algorithms/recursion/karel-1.tar.bz2 b/files/algorithms/recursion/karel-1.tar.bz2 index cee0044..d64cca6 100644 Binary files a/files/algorithms/recursion/karel-1.tar.bz2 and b/files/algorithms/recursion/karel-1.tar.bz2 differ diff --git a/files/algorithms/recursion/karel-1.tar.gz b/files/algorithms/recursion/karel-1.tar.gz index 90ac7c4..536af5a 100644 Binary files a/files/algorithms/recursion/karel-1.tar.gz and b/files/algorithms/recursion/karel-1.tar.gz differ diff --git a/files/algorithms/recursion/pyramid-slide-down.tar.bz2 b/files/algorithms/recursion/pyramid-slide-down.tar.bz2 index 8c0a57c..74db91c 100644 Binary files a/files/algorithms/recursion/pyramid-slide-down.tar.bz2 and b/files/algorithms/recursion/pyramid-slide-down.tar.bz2 differ diff --git a/files/algorithms/recursion/pyramid-slide-down.tar.gz b/files/algorithms/recursion/pyramid-slide-down.tar.gz index b6beba9..35eebe3 100644 Binary files a/files/algorithms/recursion/pyramid-slide-down.tar.gz and b/files/algorithms/recursion/pyramid-slide-down.tar.gz differ diff --git a/files/algorithms/time-complexity/extend.tar.bz2 b/files/algorithms/time-complexity/extend.tar.bz2 index 6bdf00d..2b8ba9b 100644 Binary files a/files/algorithms/time-complexity/extend.tar.bz2 and b/files/algorithms/time-complexity/extend.tar.bz2 differ diff --git a/files/algorithms/time-complexity/extend.tar.gz b/files/algorithms/time-complexity/extend.tar.gz index ac28254..ab4e23e 100644 Binary files a/files/algorithms/time-complexity/extend.tar.gz and b/files/algorithms/time-complexity/extend.tar.gz differ diff --git a/files/blog/leetcode/sort-matrix-diagonally/makefile b/files/blog/leetcode/sort-matrix-diagonally/makefile index 07bbd28..784c49b 100644 --- a/files/blog/leetcode/sort-matrix-diagonally/makefile +++ b/files/blog/leetcode/sort-matrix-diagonally/makefile @@ -13,4 +13,4 @@ format: tidy: clang-tidy *.cpp -- $(CXXFLAGS) -.PHONY: matrix-sort format tidy \ No newline at end of file +.PHONY: matrix-sort format tidy diff --git a/files/blog/leetcode/sort-matrix-diagonally/matrix-sort.cpp b/files/blog/leetcode/sort-matrix-diagonally/matrix-sort.cpp index 209b02a..99c5afb 100644 --- a/files/blog/leetcode/sort-matrix-diagonally/matrix-sort.cpp +++ b/files/blog/leetcode/sort-matrix-diagonally/matrix-sort.cpp @@ -226,4 +226,4 @@ int main() test_case_2(); return 0; -} \ No newline at end of file +} diff --git a/files/c/bonuses/03.tar.bz2 b/files/c/bonuses/03.tar.bz2 index 044df9b..630deeb 100644 Binary files a/files/c/bonuses/03.tar.bz2 and b/files/c/bonuses/03.tar.bz2 differ diff --git a/files/c/bonuses/03.tar.gz b/files/c/bonuses/03.tar.gz index a0e57b9..092989d 100644 Binary files a/files/c/bonuses/03.tar.gz and b/files/c/bonuses/03.tar.gz differ diff --git a/files/c/bonuses/04.tar.bz2 b/files/c/bonuses/04.tar.bz2 index 3fafe46..67629d5 100644 Binary files a/files/c/bonuses/04.tar.bz2 and b/files/c/bonuses/04.tar.bz2 differ diff --git a/files/c/bonuses/04.tar.gz b/files/c/bonuses/04.tar.gz index 4bd1c25..7d68c8b 100644 Binary files a/files/c/bonuses/04.tar.gz and b/files/c/bonuses/04.tar.gz differ diff --git a/files/c/bonuses/05-06.tar.bz2 b/files/c/bonuses/05-06.tar.bz2 index dfa56b0..4609983 100644 Binary files a/files/c/bonuses/05-06.tar.bz2 and b/files/c/bonuses/05-06.tar.bz2 differ diff --git a/files/c/bonuses/05-06.tar.gz b/files/c/bonuses/05-06.tar.gz index d397bb6..e2deaa0 100644 Binary files a/files/c/bonuses/05-06.tar.gz and b/files/c/bonuses/05-06.tar.gz differ diff --git a/files/c/bonuses/08.tar.bz2 b/files/c/bonuses/08.tar.bz2 index d04a5c4..2780842 100644 Binary files a/files/c/bonuses/08.tar.bz2 and b/files/c/bonuses/08.tar.bz2 differ diff --git a/files/c/bonuses/08.tar.gz b/files/c/bonuses/08.tar.gz index a135d8c..f7a4c73 100644 Binary files a/files/c/bonuses/08.tar.gz and b/files/c/bonuses/08.tar.gz differ diff --git a/files/c/bonuses/10.tar.bz2 b/files/c/bonuses/10.tar.bz2 index e232b9d..cee1622 100644 Binary files a/files/c/bonuses/10.tar.bz2 and b/files/c/bonuses/10.tar.bz2 differ diff --git a/files/c/bonuses/10.tar.gz b/files/c/bonuses/10.tar.gz index a4a5b75..b28db66 100644 Binary files a/files/c/bonuses/10.tar.gz and b/files/c/bonuses/10.tar.gz differ diff --git a/index.html b/index.html index 59010ef..3389fcd 100644 --- a/index.html +++ b/index.html @@ -14,7 +14,7 @@ - + diff --git a/search/index.html b/search/index.html index e5ea5dc..db2b1ce 100644 --- a/search/index.html +++ b/search/index.html @@ -14,7 +14,7 @@ - + diff --git a/talks/index.html b/talks/index.html index a1efb55..41d9581 100644 --- a/talks/index.html +++ b/talks/index.html @@ -14,7 +14,7 @@ - +