My Advent Of Rust, Day 4.

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

  • You have a big string input, containing representations of passports.
  • 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?

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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store