summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJesse Luehrs <doy@tozt.net>2020-12-02 00:53:09 -0500
committerJesse Luehrs <doy@tozt.net>2020-12-02 00:53:09 -0500
commite112f44360971a2909409af513be8f4df46627e5 (patch)
tree9c8335e37caeada0a4a8300d41be9d10eb025729
parenta2abe26e3190ee2105bf1d46066ae48d3c2ad4f0 (diff)
downloadadvent-of-code-e112f44360971a2909409af513be8f4df46627e5.tar.gz
advent-of-code-e112f44360971a2909409af513be8f4df46627e5.zip
puzzle 2-2
-rw-r--r--src/2020/2/mod.rs50
1 files changed, 33 insertions, 17 deletions
diff --git a/src/2020/2/mod.rs b/src/2020/2/mod.rs
index 88d3f5b..71afd7a 100644
--- a/src/2020/2/mod.rs
+++ b/src/2020/2/mod.rs
@@ -3,8 +3,8 @@ use std::io::BufRead as _;
struct Line {
c: char,
- min_times: usize,
- max_times: usize,
+ n1: usize,
+ n2: usize,
password: String,
}
@@ -19,13 +19,13 @@ impl Line {
.as_str()
.parse()
.context("invalid policy char")?;
- let min_times = captures
+ let n1 = captures
.get(1)
.unwrap()
.as_str()
.parse()
.context("invalid policy lower bound")?;
- let max_times = captures
+ let n2 = captures
.get(2)
.unwrap()
.as_str()
@@ -34,31 +34,47 @@ impl Line {
let password = captures.get(4).unwrap().as_str().to_string();
Ok(Self {
c,
- min_times,
- max_times,
+ n1,
+ n2,
password,
})
}
- fn valid(&self) -> bool {
+ fn valid_part_1(&self) -> bool {
let count = self.password.chars().filter(|c| *c == self.c).count();
- count >= self.min_times && count <= self.max_times
+ count >= self.n1 && count <= self.n2
+ }
+
+ fn valid_part_2(&self) -> bool {
+ let valid = (self.password.chars().nth(self.n1 - 1) == Some(self.c))
+ ^ (self.password.chars().nth(self.n2 - 1) == Some(self.c));
+ println!(
+ "{}-{} {}: {} ({})",
+ self.n1, self.n2, self.c, self.password, valid,
+ );
+ valid
}
}
pub fn part1() -> anyhow::Result<()> {
- let f = std::fs::File::open("data/2.txt")
- .context("couldn't find data file 2.txt")?;
- let f = std::io::BufReader::new(f);
- let lines = f
- .lines()
- .map(|l| Line::parse(&l.context("failed to read a line")?))
- .collect::<anyhow::Result<Vec<Line>>>()?;
- let count = lines.iter().filter(|l| l.valid()).count();
+ let lines = read_lines()?;
+ let count = lines.iter().filter(|l| l.valid_part_1()).count();
println!("{}", count);
Ok(())
}
pub fn part2() -> anyhow::Result<()> {
- todo!()
+ let lines = read_lines()?;
+ let count = lines.iter().filter(|l| l.valid_part_2()).count();
+ println!("{}", count);
+ Ok(())
+}
+
+fn read_lines() -> anyhow::Result<Vec<Line>> {
+ let f = std::fs::File::open("data/2.txt")
+ .context("couldn't find data file 2.txt")?;
+ let f = std::io::BufReader::new(f);
+ f.lines()
+ .map(|l| Line::parse(&l.context("failed to read a line")?))
+ .collect()
}