From 7416df5689ebafd357b9c82a7868637752bdc4ef Mon Sep 17 00:00:00 2001 From: Bert Peters Date: Wed, 28 Dec 2016 13:13:14 +0100 Subject: [PATCH] Add solutions to day 18. --- 2016/day-18/Cargo.toml | 6 ++++++ 2016/day-18/src/main.rs | 44 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 2016/day-18/Cargo.toml create mode 100644 2016/day-18/src/main.rs diff --git a/2016/day-18/Cargo.toml b/2016/day-18/Cargo.toml new file mode 100644 index 0000000..8afc8e9 --- /dev/null +++ b/2016/day-18/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "day-18" +version = "0.1.0" +authors = ["Bert Peters "] + +[dependencies] diff --git a/2016/day-18/src/main.rs b/2016/day-18/src/main.rs new file mode 100644 index 0000000..6d103d3 --- /dev/null +++ b/2016/day-18/src/main.rs @@ -0,0 +1,44 @@ +const INPUT: &'static str = ".^^^.^.^^^^^..^^^..^..^..^^..^.^.^.^^.^^....^.^...^.^^.^^.^^..^^..^.^..^^^.^^...^...^^....^^.^^^^^^^"; + +fn count_row(row: &[bool]) -> usize +{ + return row.iter().filter(|&&b| !b).count(); +} + +fn get_neighbours(row: &[bool], index: usize) -> [bool; 3] +{ + let mut output = [false; 3]; + output[0] = if index > 0 { row[index - 1] } else { false }; + output[1] = row[index]; + output[2] = if index < row.len() - 1 { row[index + 1] } else { false }; + + return output; +} + +fn solve_for(n: i32) +{ + let mut row: Vec = INPUT.chars().map(|c| c == '^').collect(); + let mut count = count_row(&row); + + for _ in 1..n { + let mut new_row = row.clone(); + + for j in 0..row.len() { + let neighbours = get_neighbours(&row, j); + new_row[j] = (neighbours[0] && neighbours[1] && !neighbours[2]) + || (!neighbours[0] && neighbours[1] && neighbours[2]) + || (neighbours[0] && !neighbours[1] && !neighbours[2]) + || (!neighbours[0] && !neighbours[1] && neighbours[2]); + } + + count += count_row(&new_row); + row = new_row; + } + + println!("{} safe spaces in {} rows", count, n); +} + +fn main() { + solve_for(40); + solve_for(400_000); +}