aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorBryan Brattlof <hello@bryanbrattlof.com>2021-11-28 14:21:57 -0500
committerBryan Brattlof <hello@bryanbrattlof.com>2021-11-29 11:20:18 -0500
commit409faea6718c170491bf58f7c20ed0280448e4ce (patch)
tree22aedc44dbf0d69cf6ca1960dac493854353e265
parenta484818d9481da5d42d7c85887062c7f8183c297 (diff)
downloadadvent-of-code-409faea6718c170491bf58f7c20ed0280448e4ce.tar.gz
advent-of-code-409faea6718c170491bf58f7c20ed0280448e4ce.tar.bz2
2020: day 15 part 2
-rw-r--r--y2020/src/d15.rs38
-rw-r--r--y2020/src/main.rs3
2 files changed, 41 insertions, 0 deletions
diff --git a/y2020/src/d15.rs b/y2020/src/d15.rs
index 7a02dba..1c0048e 100644
--- a/y2020/src/d15.rs
+++ b/y2020/src/d15.rs
@@ -1,6 +1,7 @@
use std::collections::HashMap;
const COUNT: usize = 2020;
+const PART2_COUNT: usize = 30000000;
pub fn part1<T: Iterator<Item = String>>(e: T) -> usize {
let mut i = e.collect::<String>().split(",")
@@ -24,6 +25,29 @@ pub fn part1<T: Iterator<Item = String>>(e: T) -> usize {
ls
}
+
+pub fn part2<T: Iterator<Item = String>>(e: T) -> usize {
+ let mut i = e.collect::<String>().split(",")
+ .map(|n| n.parse().unwrap())
+ .collect::<Vec<usize>>();
+
+ // add the starting values to HashMap
+ let mut m: HashMap<usize, usize> = HashMap::new();
+ i.iter()
+ .enumerate()
+ .for_each(|(i, x)| { m.insert(*x, i + 1); });
+
+ // loop through each turn updating HashMap
+ let mut ls = i.remove(i.len() - 1);
+ for t in i.len() + 1..PART2_COUNT {
+ let s = m.get(&ls).unwrap_or(&t).to_owned();
+ m.insert(ls, t);
+ ls = t - s;
+ }
+
+ ls
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -35,10 +59,24 @@ mod tests {
(1836, ["3,1,2"])
];
+ static EX2: [(usize, [&str; 1]); 7] = [
+ (175594, ["0,3,6"]), (2578, ["1,3,2"]),
+ (3544142, ["2,1,3"]), (261214, ["1,2,3"]),
+ (6895259, ["2,3,1"]), (18, ["3,2,1"]),
+ (362, ["3,1,2"])
+ ];
+
#[test]
fn test() {
for (a, i) in EX.iter() {
assert_eq!(*a, part1(i.iter().map(|x| x.to_string())));
}
}
+
+ #[test]
+ fn test2() {
+ for (a, i) in EX2.iter() {
+ assert_eq!(*a, part2(i.iter().map(|x| x.to_string())));
+ }
+ }
}
diff --git a/y2020/src/main.rs b/y2020/src/main.rs
index 5c9beb6..088eecc 100644
--- a/y2020/src/main.rs
+++ b/y2020/src/main.rs
@@ -146,5 +146,8 @@ fn main() {
if args.is_empty() || args.contains("15") {
let a = d15::part1(get_input_for_day(15));
println!("2020: day 15 part 1: {}", a);
+
+ let a = d15::part2(get_input_for_day(15));
+ println!("2020: day 15 part 2: {}", a);
}
}