Compare commits

..

4 Commits

Author SHA1 Message Date
c9e45c4685 day10 2023-12-28 13:36:06 -05:00
b44361e14d day9 2023-12-28 13:35:58 -05:00
90561f8fa9 day8 2023-12-28 13:35:39 -05:00
2c499e9efe day7 2023-12-28 13:35:25 -05:00
7 changed files with 538 additions and 0 deletions

52
Cargo.lock generated
View File

@ -9,10 +9,21 @@ dependencies = [
"aoc-runner", "aoc-runner",
"aoc-runner-derive", "aoc-runner-derive",
"itertools", "itertools",
"lazy_static",
"regex",
"strum", "strum",
"strum_macros", "strum_macros",
] ]
[[package]]
name = "aho-corasick"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2969dcb958b36655471fc61f7e416fa76033bdd4bfed0678d8fee1e2d07a1f0"
dependencies = [
"memchr",
]
[[package]] [[package]]
name = "aoc-runner" name = "aoc-runner"
version = "0.3.0" version = "0.3.0"
@ -69,6 +80,18 @@ version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c"
[[package]]
name = "lazy_static"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "memchr"
version = "2.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f665ee40bc4a3c5590afb1e9677db74a508659dfd71e126420da8274909a0167"
[[package]] [[package]]
name = "proc-macro2" name = "proc-macro2"
version = "1.0.71" version = "1.0.71"
@ -87,6 +110,35 @@ dependencies = [
"proc-macro2", "proc-macro2",
] ]
[[package]]
name = "regex"
version = "1.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "380b951a9c5e80ddfd6136919eef32310721aa4aacd4889a8d39124b026ab343"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f804c7828047e88b2d32e2d7fe5a105da8ee3264f01902f796c8e067dc2483f"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f"
[[package]] [[package]]
name = "rustversion" name = "rustversion"
version = "1.0.14" version = "1.0.14"

View File

@ -14,3 +14,5 @@ aoc-runner-derive = "0.3.0"
itertools = "0.12.0" itertools = "0.12.0"
strum = "0.25.0" strum = "0.25.0"
strum_macros = "0.25" strum_macros = "0.25"
lazy_static = "1.4.0"
regex = "1.10.2"

106
src/day10.rs Normal file
View File

@ -0,0 +1,106 @@
use std::collections::HashMap;
use aoc_runner_derive::{aoc, aoc_generator};
use itertools::Itertools;
#[aoc_generator(day10)]
fn parse(input: &str) -> Vec<u32> {
input.lines().map(str::parse).map(Result::unwrap).sorted().collect_vec()
}
#[aoc(day10, part1)]
fn part1(input: &Vec<u32>) -> u32 {
let mut count1 = 1;
let mut count3 = 1;
for (lhs, rhs) in input.iter().tuple_windows() {
match rhs - lhs {
1 => count1 += 1,
3 => count3 += 1,
_ => unreachable!()
}
}
count1 * count3
}
#[aoc(day10, part2)]
fn part2(input: &Vec<u32>) -> i64 {
let mut ans = HashMap::new();
ans.insert(0, 1);
for adapter in input.iter().cloned().map(|x| x as i32) {
let to_insert = ans.get(&(adapter as i32 - 1)).unwrap_or(&0) + ans.get(&(adapter as i32 - 2)).unwrap_or(&0) + ans.get(&(adapter as i32 - 3)).unwrap_or(&0);
ans.insert(adapter, to_insert.clone());
}
ans[&(*input.last().unwrap() as i32)]
}
#[cfg(test)]
mod tests {
use super::*;
const EX: &str = r"16
10
15
5
1
11
7
19
6
12
4";
const EX_2: &str = r"28
33
18
42
31
14
46
20
48
47
24
23
49
45
19
38
39
11
1
32
25
35
8
17
7
9
4
2
34
10
3";
#[test]
fn part1_example() {
assert_eq!(part1(&parse(EX)), 35);
}
#[test]
fn part1_example2() {
assert_eq!(part1(&parse(EX_2)), 220);
}
#[test]
fn part2_example() {
assert_eq!(part2(&parse(EX)), 8);
}
#[test]
fn part2_example2() {
assert_eq!(part2(&parse(EX_2)), 19208);
}
}

119
src/day7.rs Normal file
View File

@ -0,0 +1,119 @@
use std::collections::{HashMap, VecDeque};
use aoc_runner_derive::{aoc, aoc_generator};
use regex::Regex;
const GOAL: &str = "shiny gold";
lazy_static! {
static ref LINE_RE: Regex = Regex::new(r"(\w+ \w+) bags contain (.*)").unwrap();
static ref ITEM_RE: Regex = Regex::new(r"(\d+) (\w+ \w+) bags?").unwrap();
}
#[aoc_generator(day7)]
fn parse(input: &str) -> HashMap<String, Vec<(usize, String)>> {
let mut bags = HashMap::<String, Vec<(usize, String)>>::new();
for line in input.lines() {
if let Some((item, items)) = LINE_RE
.captures(line.as_ref())
.and_then(|captures| {
Some((captures.get(1)?.as_str(), captures.get(2)?.as_str()))
}) {
bags.insert(
item.to_string(),
ITEM_RE
.captures_iter(items)
.filter_map(|captures| {
Some((
captures.get(1)?.as_str().parse().ok()?,
captures.get(2)?.as_str().to_string(),
))
}).collect()
);
}
}
bags
}
struct Expand<'a> {
bags: &'a HashMap<String, Vec<(usize, String)>>,
queue: VecDeque<(usize, &'a str)>
}
fn expand<'a>(bags: &'a HashMap<String, Vec<(usize, String)>>, bag: &str) -> Expand<'a> {
Expand {
bags,
queue: bags.get(bag).map_or_else(VecDeque::new, |items| {
items.iter()
.map(|(count, item)| (*count, item.as_str()))
.collect()
}),
}
}
impl<'a> Iterator for Expand<'a> {
type Item = (usize, &'a str);
fn next(&mut self) -> Option<Self::Item> {
self.queue.pop_front().map(|(count, item)| {
if let Some(items) = self.bags.get(item) {
for (subcount, subitem) in items {
self.queue.push_back((count * subcount, subitem));
}
}
(count, item)
})
}
}
#[aoc(day7, part1)]
fn part1(bags: &HashMap<String, Vec<(usize, String)>>) -> usize {
bags.keys()
.filter(|key| expand(&bags, key).any(|(_, item)| item == GOAL))
.count()
}
#[aoc(day7, part2)]
fn part2(bags: &HashMap<String, Vec<(usize, String)>>) -> usize {
expand(bags, GOAL).map(|(count, _)| count).sum()
}
#[cfg(test)]
mod tests {
use super::*;
const EX: &str = r"light red bags contain 1 bright white bag, 2 muted yellow bags.
dark orange bags contain 3 bright white bags, 4 muted yellow bags.
bright white bags contain 1 shiny gold bag.
muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.
shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.
dark olive bags contain 3 faded blue bags, 4 dotted black bags.
vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.
faded blue bags contain no other bags.
dotted black bags contain no other bags.";
const EX_2: &str = r"shiny gold bags contain 2 dark red bags.
dark red bags contain 2 dark orange bags.
dark orange bags contain 2 dark yellow bags.
dark yellow bags contain 2 dark green bags.
dark green bags contain 2 dark blue bags.
dark blue bags contain 2 dark violet bags.
dark violet bags contain no other bags.";
#[test]
fn part1_example() {
assert_eq!(part1(&parse(EX)), 4);
}
#[test]
fn part2_example() {
assert_eq!(part2(&parse(EX)), 32);
}
#[test]
fn part2_example2() {
assert_eq!(part2(&parse(EX_2)), 126);
}
}

180
src/day8.rs Normal file
View File

@ -0,0 +1,180 @@
use aoc_runner_derive::{aoc, aoc_generator};
use itertools::Itertools;
#[aoc_generator(day8)]
fn parse(input: &str) -> Box<[Instruction]> {
let input: Vec<Instruction> = input.lines()
.map(|line| {
let (instruction, arg) = line.split(' ').collect_tuple().unwrap();
(instruction, arg.parse::<i32>().unwrap()).into()
}).collect_vec();
input.try_into().unwrap()
}
use Instruction::*;
#[derive(Debug, Clone, Copy)]
enum Instruction {
ACC(i32),
JMP(i32),
NOP(i32)
}
impl From<(&str, i32)> for Instruction {
fn from(value: (&str, i32)) -> Self {
match value {
(i, v) if i == "acc" => ACC(v),
(i, v) if i == "jmp" => JMP(v),
(i, v) if i == "nop" => NOP(v),
_ => unreachable!()
}
}
}
#[aoc(day8, part1)]
fn part1(input: &[Instruction]) -> i32 {
let mut visited: Vec<bool> = vec![false; input.len()];
let mut next = 0;
let mut acc = 0;
loop {
let inst = &input[next];
if visited[next] {
break;
}
visited[next] = true;
match inst {
ACC(arg) => acc += arg,
JMP(arg) => {next = (next as i32 + *arg) as usize; continue;},
NOP(_) => {},
}
next += 1;
}
acc
}
#[aoc(day8, part2)]
fn part2(input: &[Instruction]) -> i32 {
let mut visited: Vec<bool> = vec![false; input.len()];
let mut next = 0;
let mut acc = 0;
loop {
let inst = &input[next];
if visited[next] {
break;
}
visited[next] = true;
match inst {
ACC(arg) => acc += arg,
JMP(arg) => {next = (next as i32 + *arg) as usize; continue;},
NOP(_) => {},
}
next += 1;
}
let mut landing_spots = vec![false; input.len() + 1];
let mut i = input.len();
loop {
landing_spots[i] = true;
i -= 1;
if let JMP(x) = input[i] {
if x < 0 {
break;
}
}
}
let start = i;
let swap = if visited[i] {
i
} else {
loop {
i -= 1;
if landing_spots[i] {
continue;
} else if let NOP(x) = input[i] {
if visited[i] && landing_spots[((i as i32) + x) as usize] {
break i;
}
} else if let JMP(x) = input[i] {
if !visited[i]
&& landing_spots[((i as i32) + x) as usize]
&& !landing_spots[i]
{
let mut j = i - 1;
loop {
if matches!(input[j], JMP(_)) {
break;
}
j -= 1;
}
if visited[j] {
break j;
} else {
landing_spots[j + 1..=i].iter_mut().for_each(|a| {
*a = true;
});
i = start;
}
}
}
}
};
let mut program = input.to_vec();
program[swap] = match program[swap] {
ACC(_) => unreachable!(),
JMP(x) => NOP(x),
NOP(x) => JMP(x),
};
let mut next = 0;
let mut acc = 0;
loop {
if next >= program.len() {
break;
}
let inst = &program[next];
match inst {
ACC(arg) => acc += arg,
JMP(arg) => {next = (next as i32 + *arg) as usize; continue;},
NOP(_) => {},
}
next += 1;
}
acc
}
#[cfg(test)]
mod tests {
use super::*;
const EX: &str = r"nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6";
#[test]
fn part1_example() {
assert_eq!(part1(&parse(EX)), 5);
}
#[test]
fn part2_example() {
assert_eq!(part2(&parse(EX)), 8);
}
}

73
src/day9.rs Normal file
View File

@ -0,0 +1,73 @@
use aoc_runner_derive::{aoc, aoc_generator};
use itertools::Itertools;
const PREAMBLE_LEN: usize = 25;
#[aoc_generator(day9)]
fn parse(input: &str) -> Vec<u64> {
input.lines().map(str::parse).map(Result::unwrap).collect_vec()
}
#[aoc(day9, part1)]
fn part1(input: &Vec<u64>) -> u64 {
for i in PREAMBLE_LEN..input.len() {
if let None = input[i - PREAMBLE_LEN..i]
.iter()
.combinations(2)
.find(|x| x.iter().cloned().sum::<u64>() == input[i]) {
return input[i];
}
}
unreachable!()
}
#[aoc(day9, part2)]
fn part2(input: &Vec<u64>) -> u64 {
let to_find = part1(input);
for len in 2..input.len() {
if let Some(nums) = input
.windows(len)
.find(|x| x.iter().cloned().sum::<u64>() == to_find) {
return nums.iter().min().unwrap() + nums.iter().max().unwrap();
}
}
unreachable!()
}
#[cfg(test)]
mod tests {
use super::*;
const EX: &str = r"35
20
15
25
47
40
62
55
65
95
102
117
150
182
127
219
299
277
309
576";
#[test]
fn part1_example() {
assert_eq!(part1(&parse(EX)), 127);
}
#[test]
fn part2_example() {
assert_eq!(part2(&parse(EX)), 62);
}
}

View File

@ -1,3 +1,7 @@
mod day10;
mod day9;
mod day8;
mod day7;
mod day6; mod day6;
mod day5; mod day5;
mod day1; mod day1;
@ -8,5 +12,7 @@ extern crate aoc_runner;
#[macro_use] #[macro_use]
extern crate aoc_runner_derive; extern crate aoc_runner_derive;
#[macro_use]
extern crate lazy_static;
aoc_lib!{ year = 2020 } aoc_lib!{ year = 2020 }