Advent of Rust // Day 6
Easy one. I still haven’t figured out why Rust sometimes can not infer types, like with the hash set below.
fn position_after_unique_characters(input: &str, len: usize) -> Result<usize, String> {
if len > input.len() {
return Err(format!("String '{input}' is shorter than {len} characters"));
}
for index in 0..input.len() - len {
let chars: HashSet<char> = HashSet::from_iter((&input[index..index + len]).chars());
if chars.len() == len as usize {
return Ok(index + len);
}
}
return Err(format!("String '{input}' does not contain a series of {len} unique characters"));
}
fn main() {
let input = fs::read_to_string("input/day06.txt").unwrap();
println!("Part One: {}", position_after_unique_characters(&input, 4).unwrap());
println!("Part Two: {}", position_after_unique_characters(&input, 14).unwrap());
}
If you’ve been following my little series, you might have noticed that there finally is some error handling. Until now, I only panic’d or not giving a fuck. It’s the first shot, so there’s probably room for improvement. Testing for errors was straightforward:
#[test]
fn no_unique_characters() {
assert_eq!(
"String 'aaaa' does not contain a series of 2 unique characters",
position_after_unique_characters("aaaa", 2).unwrap_err()
);
}
#[test]
fn input_is_shorter_than_length() {
assert_eq!(
"String 'ab' is shorter than 3 characters",
position_after_unique_characters("ab", 3).unwrap_err()
);
}
The full source and solutions for the others puzzles of Advent of Code can be found in my GitHub repository.
Comments
You can leave a comment by replying to this post on Mastodon.