diff options
author | Prefetch | 2023-02-25 11:41:27 +0100 |
---|---|---|
committer | Prefetch | 2023-02-25 11:41:27 +0100 |
commit | 3b877bf4cc667eb8bcc787d145203600a4dba2d2 (patch) | |
tree | c1d247def29fcb58ae28e4ae4e4d73d1b4e1b27f /d18 |
Initial commit
Diffstat (limited to 'd18')
-rw-r--r-- | d18/Cargo.toml | 6 | ||||
-rw-r--r-- | d18/input.txt | 1 | ||||
-rw-r--r-- | d18/src/main.rs | 62 |
3 files changed, 69 insertions, 0 deletions
diff --git a/d18/Cargo.toml b/d18/Cargo.toml new file mode 100644 index 0000000..02d725e --- /dev/null +++ b/d18/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "d18" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/d18/input.txt b/d18/input.txt new file mode 100644 index 0000000..2036710 --- /dev/null +++ b/d18/input.txt @@ -0,0 +1 @@ +.^^^.^.^^^^^..^^^..^..^..^^..^.^.^.^^.^^....^.^...^.^^.^^.^^..^^..^.^..^^^.^^...^...^^....^^.^^^^^^^ diff --git a/d18/src/main.rs b/d18/src/main.rs new file mode 100644 index 0000000..a9410f2 --- /dev/null +++ b/d18/src/main.rs @@ -0,0 +1,62 @@ +use std::fs; + +fn solve_puzzle(first: &str, num_rows: usize) -> usize { + let mut total = first.matches('.').count(); + + let mut tiles: Vec<char> = first.chars().collect(); + for _i in 1..num_rows { + let mut next = Vec::new(); + + for j in 0..tiles.len() { + let is_trap; + + // At left wall + if j == 0 { + is_trap = tiles[j + 1] == '^'; // rule 2 + 4 + // At right wall + } else if j == tiles.len() - 1 { + is_trap = tiles[j - 1] == '^'; // rule 1 + 3 + // Away from the walls + } else { + is_trap = tiles[j - 1] == '^' && tiles[j + 1] == '.' // rule 1 + 3 + || tiles[j - 1] == '.' && tiles[j + 1] == '^'; // rule 2 + 4 + } + + next.push(if is_trap { '^' } else { '.' }); + } + + tiles = next; + total += tiles.iter().filter(|&c| *c == '.').count(); + } + + total +} + +fn main() { + // Read my personal puzzle input + let input = fs::read_to_string("input.txt").unwrap(); + let first = input.trim_end(); + + // Part 1 gives 1939 for me + println!("Part 1 solution: {}", solve_puzzle(first, 40)); + + // Part 2 gives 19999535 for me + println!("Part 1 solution: {}", solve_puzzle(first, 400000)); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn part1_example1() { + let input = "..^^."; + assert_eq!(solve_puzzle(input, 3), 6); + } + + #[test] + fn part1_example2() { + let input = ".^^.^.^^^^"; + assert_eq!(solve_puzzle(input, 10), 38); + } +} |