Day 10: Hoof It
Megathread guidelines
- Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
- You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL
FAQ
- What is this?: Here is a post with a large amount of details: https://programming.dev/post/6637268
- Where do I participate?: https://adventofcode.com/
- Is there a leaderboard for the community?: We have a programming.dev leaderboard with the info on how to join in this post: https://programming.dev/post/6631465
You are viewing a single thread.
View all comments 3 points
Rust
Definitely a nice and easy one, I accidentally solved part 2 first, because I skimmed the challenge and missed the unique part.
#[cfg(test)]
mod tests {
const DIR_ORDER: [(i8, i8); 4] = [(-1, 0), (0, 1), (1, 0), (0, -1)];
fn walk_trail(board: &Vec<Vec<i8>>, level: i8, i: i8, j: i8) -> Vec<(i8, i8)> {
let mut paths = vec![];
if i < 0 || j < 0 {
return paths;
}
let actual_level = match board.get(i as usize) {
None => return paths,
Some(line) => match line.get(j as usize) {
None => return paths,
Some(c) => c,
},
};
if *actual_level != level {
return paths;
}
if *actual_level == 9 {
return vec![(i, j)];
}
for dir in DIR_ORDER.iter() {
paths.extend(walk_trail(board, level + 1, i + dir.0, j + dir.1));
}
paths
}
fn count_unique(p0: &Vec<(i8, i8)>) -> u32 {
let mut dedup = vec![];
for p in p0.iter() {
if !dedup.contains(p) {
dedup.push(*p);
}
}
dedup.len() as u32
}
#[test]
fn day10_part1_test() {
let input = std::fs::read_to_string("src/input/day_10.txt").unwrap();
let board = input
.trim()
.split('\n')
.map(|line| {
line.chars()
.map(|c| {
if c == '.' {
-1
} else {
c.to_digit(10).unwrap() as i8
}
})
.collect::<Vec<i8>>()
})
.collect::<Vec<Vec<i8>>>();
let mut total = 0;
for (i, row) in board.iter().enumerate() {
for (j, pos) in row.iter().enumerate() {
if *pos == 0 {
let all_trails = walk_trail(&board, 0, i as i8, j as i8);
total += count_unique(&all_trails);
}
}
}
println!("{}", total);
}
#[test]
fn day10_part2_test() {
let input = std::fs::read_to_string("src/input/day_10.txt").unwrap();
let board = input
.trim()
.split('\n')
.map(|line| {
line.chars()
.map(|c| {
if c == '.' {
-1
} else {
c.to_digit(10).unwrap() as i8
}
})
.collect::<Vec<i8>>()
})
.collect::<Vec<Vec<i8>>>();
let mut total = 0;
for (i, row) in board.iter().enumerate() {
for (j, pos) in row.iter().enumerate() {
if *pos == 0 {
total += walk_trail(&board, 0, i as i8, j as i8).len();
}
}
}
println!("{}", total);
}
}