summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorcos <cos>2022-12-09 16:58:38 +0000
committercos <cos>2022-12-09 16:59:12 +0000
commit25bee76f74d3d178946522e29983fde90edc4df6 (patch)
tree7f7b26720bb1d0814f0fe02f721d905d053d565c
parent377a8057cc73fb19cea31a3f136509dad1070415 (diff)
downloadadventofcode-25bee76f74d3d178946522e29983fde90edc4df6.zip
Add day06, 2022
-rw-r--r--2022/rust/Cargo.toml2
-rw-r--r--2022/rust/day06/Cargo.toml8
-rw-r--r--2022/rust/day06/src/main.rs51
3 files changed, 60 insertions, 1 deletions
diff --git a/2022/rust/Cargo.toml b/2022/rust/Cargo.toml
index e127354..4e87017 100644
--- a/2022/rust/Cargo.toml
+++ b/2022/rust/Cargo.toml
@@ -5,7 +5,7 @@ members = [
"day03",
"day04",
"day05",
-# "day06",
+ "day06",
# "day07",
# "day08",
# "day09",
diff --git a/2022/rust/day06/Cargo.toml b/2022/rust/day06/Cargo.toml
new file mode 100644
index 0000000..cd279fb
--- /dev/null
+++ b/2022/rust/day06/Cargo.toml
@@ -0,0 +1,8 @@
+[package]
+name = "day06"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+aoc = { path = "../../../common/rust/aoc" }
+anyhow = "1.0"
diff --git a/2022/rust/day06/src/main.rs b/2022/rust/day06/src/main.rs
new file mode 100644
index 0000000..d7bae65
--- /dev/null
+++ b/2022/rust/day06/src/main.rs
@@ -0,0 +1,51 @@
+use {
+ anyhow::{
+ anyhow,
+ Context,
+ Result,
+ },
+ std::{
+ env::args,
+ fs::read_to_string,
+ path::Path,
+ },
+};
+
+fn read_input<T: AsRef<Path>>(filename: T) -> Result<String> {
+ read_to_string(filename).context("Could not read {filename}")
+}
+
+fn find_sequence(input: &str, len: usize) -> Option<usize> {
+ input.as_bytes().windows(len).enumerate().find_map(|(pos, win)| {
+ for i in 0..len {
+ if win[(i + 1)..].contains(&win[i]) {
+ return None
+ }
+ }
+ Some(pos + len)
+ })
+}
+
+fn part1(input: &str) -> Result<usize> {
+ find_sequence(input, 4).ok_or_else(|| anyhow!("No match found"))
+}
+
+fn part2(input: &str) -> Result<usize> {
+ find_sequence(input, 14).ok_or_else(|| anyhow!("No match found"))
+}
+
+fn main() -> Result<()> {
+ let ( do_part_1, do_part_2 ) = aoc::do_parts();
+
+ let filename = args().nth(1).ok_or_else(|| anyhow!("Missing input filename"))?;
+ let input = read_input(filename).context("Could not read input")?;
+ if do_part_1 {
+ let solution = part1(&input).context("No solution for part 1")?;
+ println!("Part1, solution found to be: {}", solution);
+ }
+ if do_part_2 {
+ let solution = part2(&input).context("No solution for part 2")?;
+ println!("Part2, solution found to be: {}", solution);
+ }
+ Ok(())
+}