My Advent Of Rust, Day 4.

I’ve always considered programming challenges a fun way of experimenting new languages.

For this edition of advent of code (2020), i decided i would give Rust a try.

  • On double newline, you have a passport.
  • Each valid passport consists of the following fields: “byr”, “iyr”, “eyr”, “hgt”, “hcl”, “ecl”, “pid”.
  • Find all valid passports.
let result = fs::read_to_string("input_day_four.txt").unwrap();
let passports = result.split("\n\n");
let passports: Vec<&str> = fs::read_to_string("input_day_four.txt")
.unwrap()
.split("\n\n")
validPassportCounter := 0
for _, passport := range passports {
control := map[string]struct{}{
"byr": struct{}{},
"iyr": struct{}{},
"eyr": struct{}{},
"hgt": struct{}{},
"hcl": struct{}{},
"ecl": struct{}{},
"pid": struct{}{},
}
for i, ch := range passport {
if ch == ':' {
delete(control, passport[i-3:i])
}
}
if len(control) == 0 {
validPassportCounter++
}
}
validPassportCounter := 0
for _, passport := range passports {
control := 0
fields := strings.Fields(passport)
for _, field := range fields {
if strings.HasPrefix(field, "byr") || strings.HasPrefix(field, "iyr") ||
strings.HasPrefix(field, "eyr") || strings.HasPrefix(field, "hgt") || strings.HasPrefix(field, "hcl") ||
strings.HasPrefix(field, "ecl") || strings.HasPrefix(field, "pid") {
control++
}
}
if control == 7 {
validPassportCounter++
}
}

So i went back to sketching… what was i really trying to do?

I have a vector of references to strings to which i wanted to filter the ones containing the right values and then count the collected values.

let valid_passports = passports
.filter()
.count();
fn check_validity_part_1(passport: &str) -> bool {
let fields = vec!["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"];
fields.iter().all(|field| {
passport
.split_ascii_whitespace()
.any(|passport_field| passport_field.starts_with(field))
})
}
let result = fs::read_to_string("input_day_four.txt").unwrap();let passports = result.split("\n\n");let valid_passports = passports
.filter(|passport| check_validity_part_1(passport))
.count();
println!("{}", valid_passports);

Some lessons to myself: don’t fight the compiler. If your approach/pattern is not working, it is probably because you probably cannot use this same pattern using Rust. Stop, re-evaluate, read the documentation, and surely you’ll find a way of solving the problem.

If this was the optimal approach… well, that should be re-evaluated, once i have a better knowledge of Rust :)

Following my curiosity. https://seomis.cc