Jorge-Alda / AoC2022

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Advent of Code 2022

This year I will try to solve each puzzle in both Python and Rust.

Learning Rust

Day 01

  • Read file (shorter way):
text = include_str!("input");
  • Convert str to numeric types:

    • Annotating the variable:
      let x: u32 = "4".parse().unwrap(); 
    • Using "turbofish":
      let x = "4".parse::<u32>().unwrap();
  • Operations with iterators, including sorted, rev, cartesian_product, etc

[dependencies]
itertools = "0.10.5"
use itertools.Itertools;

Day 07

Filtering values from a HashMap needs two de-references: values() (or keys(), items()) return references so not to consume the map, and filter() also doesn't consume its arguments:

use std::collections::HashMap;

let mut map: HashMap<String, u32> = HashMap::new();

//...

let total = map.values().filter(|x| **x > 0).sum();

Day 08

Debugging Rust with the extension CodeLLDB.

Day 09

  • Implementing From to convert to a custom enum/struct
use std::convert::From;

struct MyStruct {
  //...
}

impl MyStruct {
  fn From<i32>(x: i32) -> Self {
    //...
  }
}
  • Appending the content of a vector into other vector:
let mut v1 = vec![1, 2, 3];
let mut v2 = vec![4, 5, 6];

v1.append(&mut v2);
assert_eq![v1, vec![1, 2, 3, 4, 5, 6]];
assert_eq![v2, []];

Note that the copied vector needs to be passed as &mut, as it will be emptied by append.

Day 13

  • Using serde_json to parse a list of values and store it in a Value.

  • impl-ementing the PartialOrd and Ord traits to compare and sort structs or enums.

    • Traits cannot be implemented in objects defined in a different file.

Day 15

  • Regex with the crate Regex.
  • Syntax for impl-ementing Debug or Display: the macro write! modifies the Formatter object and returns a fmt::Result:
impl Display for MyStruct {
  fn fmt(&self, f_ &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    let s = String::new();
    // ... obtain s
    write!(f, "{}", s)
  }
}
  • Beware! Numerical overflows don't give a warning!

About


Languages

Language:Python 58.9%Language:Rust 41.1%