Import aoc2022 history into 2022/
git-subtree-dir: 2022 git-subtree-mainline:addb35fc75git-subtree-split:e5d89711e2
This commit is contained in:
commit
284b85580d
22 files changed
+1552
No files matched your search
@@ -0,0 +1,60 @@
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use itertools::Itertools;
|
||||
use std::io::BufRead;
|
||||
|
||||
#[aoc_generator(day1)]
|
||||
// Sum the calories of each elf's food items
|
||||
fn parse(input: &[u8]) -> Vec<u64> {
|
||||
let mut result = Vec::new();
|
||||
let mut cur_elf = 0u64;
|
||||
for line in input.lines() {
|
||||
if let Ok(calories) = line.unwrap().parse::<u64>() {
|
||||
cur_elf += calories
|
||||
} else {
|
||||
result.push(cur_elf);
|
||||
cur_elf = 0
|
||||
}
|
||||
}
|
||||
result.push(cur_elf);
|
||||
result
|
||||
}
|
||||
|
||||
#[aoc(day1, part1)]
|
||||
fn part1(input: &[u64]) -> u64 {
|
||||
*input.iter().max().unwrap()
|
||||
}
|
||||
|
||||
#[aoc(day1, part2)]
|
||||
fn part2(input: &[u64]) -> u64 {
|
||||
input.iter().sorted().rev().take(3).sum::<u64>()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &[u8] = b"1000
|
||||
2000
|
||||
3000
|
||||
|
||||
4000
|
||||
|
||||
5000
|
||||
6000
|
||||
|
||||
7000
|
||||
8000
|
||||
9000
|
||||
|
||||
10000";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(&parse(EXAMPLE)), 24000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(&parse(EXAMPLE)), 45000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
use std::{io::BufRead, str::FromStr};
|
||||
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
|
||||
#[derive(Eq, PartialEq, Clone, Copy)]
|
||||
pub enum Shape {
|
||||
Rock,
|
||||
Paper,
|
||||
Scissors,
|
||||
}
|
||||
|
||||
impl FromStr for Shape {
|
||||
type Err = Box<dyn std::error::Error>;
|
||||
fn from_str(value: &str) -> Result<Self, Self::Err> {
|
||||
match value {
|
||||
"A" | "X" => Ok(Self::Rock),
|
||||
"B" | "Y" => Ok(Self::Paper),
|
||||
"C" | "Z" => Ok(Self::Scissors),
|
||||
c => Err(format!("Invalid shape `{c:?}`").into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Shape {
|
||||
fn fight(&self, opponent: &Shape) -> Outcome {
|
||||
match (self, opponent) {
|
||||
(Self::Rock, Self::Scissors) | (Self::Scissors, Self::Paper) | (Self::Paper, Self::Rock) => Outcome::Win,
|
||||
_ if self == opponent => Outcome::Tie,
|
||||
_ => Outcome::Lose,
|
||||
}
|
||||
}
|
||||
fn score(&self, opponent: &Shape) -> u64 {
|
||||
self.points() + self.fight(opponent).points()
|
||||
}
|
||||
fn points(&self) -> u64 {
|
||||
match self {
|
||||
Shape::Rock => 1,
|
||||
Shape::Paper => 2,
|
||||
Shape::Scissors => 3,
|
||||
}
|
||||
}
|
||||
// Return the Shape that will produce the desired outcome against us for the opponent
|
||||
fn fix_round(&self, goal: &Outcome) -> Shape {
|
||||
match goal {
|
||||
Outcome::Tie => *self,
|
||||
Outcome::Win => match self {
|
||||
Shape::Rock => Shape::Paper,
|
||||
Shape::Paper => Shape::Scissors,
|
||||
Shape::Scissors => Shape::Rock,
|
||||
},
|
||||
Outcome::Lose => match self {
|
||||
Shape::Rock => Shape::Scissors,
|
||||
Shape::Paper => Shape::Rock,
|
||||
Shape::Scissors => Shape::Paper,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum Outcome {
|
||||
Win,
|
||||
Lose,
|
||||
Tie,
|
||||
}
|
||||
|
||||
impl Outcome {
|
||||
fn points(&self) -> u64 {
|
||||
match self {
|
||||
Self::Win => 6,
|
||||
Self::Tie => 3,
|
||||
Self::Lose => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for Outcome {
|
||||
type Err = Box<dyn std::error::Error>;
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"X" => Ok(Self::Lose),
|
||||
"Y" => Ok(Self::Tie),
|
||||
"Z" => Ok(Self::Win),
|
||||
_ => Err(format!("Invalid outcome : `{s}").into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Move {
|
||||
ours: Shape,
|
||||
theirs: Shape,
|
||||
}
|
||||
|
||||
impl FromStr for Move {
|
||||
type Err = Box<dyn std::error::Error>;
|
||||
fn from_str(value: &str) -> Result<Self, Self::Err> {
|
||||
let (theirs, ours) = value.split_once(" ").ok_or("Unable to split")?;
|
||||
Ok(Move {
|
||||
ours: ours.parse()?,
|
||||
theirs: theirs.parse()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Move {
|
||||
fn score(&self) -> u64 {
|
||||
self.ours.score(&self.theirs)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MoveGoal {
|
||||
theirs: Shape,
|
||||
goal: Outcome,
|
||||
}
|
||||
|
||||
impl FromStr for MoveGoal {
|
||||
type Err = Box<dyn std::error::Error>;
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let (theirs, goal) = s.split_once(" ").ok_or("Unable to split")?;
|
||||
Ok(MoveGoal {
|
||||
theirs: theirs.parse()?,
|
||||
goal: goal.parse()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl MoveGoal {
|
||||
fn get_move(&self) -> Move {
|
||||
Move {
|
||||
theirs: self.theirs,
|
||||
ours: self.theirs.fix_round(&self.goal),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[aoc_generator(day2, part1)]
|
||||
fn parse_part1(input: &[u8]) -> Vec<Move> {
|
||||
input.lines().map(|l| l.unwrap().parse().unwrap()).collect()
|
||||
}
|
||||
#[aoc_generator(day2, part2)]
|
||||
fn parse_part2(input: &[u8]) -> Vec<MoveGoal> {
|
||||
input.lines().map(|l| l.unwrap().parse().unwrap()).collect()
|
||||
}
|
||||
|
||||
#[aoc(day2, part1)]
|
||||
fn part1(input: &[Move]) -> u64 {
|
||||
input.iter().map(|m| m.score()).sum()
|
||||
}
|
||||
|
||||
#[aoc(day2, part2)]
|
||||
fn part2(input: &[MoveGoal]) -> u64 {
|
||||
input.iter().map(|mg| mg.get_move().score()).sum()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &[u8] = b"A Y
|
||||
B X
|
||||
C Z";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(&parse_part1(EXAMPLE)), 15);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(&parse_part2(EXAMPLE)), 12);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use itertools::Itertools;
|
||||
use std::fmt::Display;
|
||||
|
||||
struct Rucksack {
|
||||
items: Vec<u8>,
|
||||
}
|
||||
|
||||
impl From<&[u8]> for Rucksack {
|
||||
fn from(s: &[u8]) -> Self {
|
||||
Self { items: s.to_vec() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Rucksack {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_fmt(format_args!(
|
||||
"{}{}",
|
||||
String::from_utf8_lossy(self.compartments()[0]),
|
||||
String::from_utf8_lossy(self.compartments()[1])
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl Rucksack {
|
||||
fn compartments(&self) -> [&[u8]; 2] {
|
||||
let tup = self.items.split_at(self.items.len() / 2);
|
||||
[tup.0, tup.1]
|
||||
}
|
||||
fn common(&self) -> u8 {
|
||||
for item in self.compartments()[0] {
|
||||
if self.compartments()[1].contains(item) {
|
||||
return *item;
|
||||
}
|
||||
}
|
||||
panic!("Common item not found");
|
||||
}
|
||||
fn common_with(&self, other: &[u8]) -> impl Iterator<Item = u8> {
|
||||
self.compartments()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|c| other.contains(c))
|
||||
.cloned()
|
||||
}
|
||||
}
|
||||
|
||||
fn priority(c: u8) -> u8 {
|
||||
if c.is_ascii_uppercase() {
|
||||
c - b'A' + 27
|
||||
} else if c.is_ascii_lowercase() {
|
||||
c - b'a' + 1
|
||||
} else {
|
||||
panic!("Invalid item {c}")
|
||||
}
|
||||
}
|
||||
|
||||
#[aoc_generator(day3)]
|
||||
fn parse(input: &[u8]) -> Vec<Rucksack> {
|
||||
input.split(|i| *i == b'\n').map(|x| x.into()).collect()
|
||||
}
|
||||
|
||||
#[aoc(day3, part1)]
|
||||
fn part1(input: &[Rucksack]) -> u64 {
|
||||
input.iter().map(|sack| priority(sack.common()) as u64).sum()
|
||||
}
|
||||
|
||||
#[aoc(day3, part2)]
|
||||
fn part2(input: &[Rucksack]) -> u64 {
|
||||
let mut total = 0u64;
|
||||
for sacks in input.chunks(3) {
|
||||
let commons_1 = sacks[0].common_with(&sacks[1].items).unique().collect_vec();
|
||||
let commons = sacks[2].common_with(&commons_1).unique().collect_vec();
|
||||
|
||||
if commons.len() != 1 {
|
||||
panic!(
|
||||
"Wrong number ({}) of commons for sacks {} {} {}",
|
||||
commons.len(),
|
||||
sacks[0],
|
||||
sacks[1],
|
||||
sacks[2]
|
||||
);
|
||||
}
|
||||
total += priority(commons[0]) as u64
|
||||
}
|
||||
total
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &[u8] = b"vJrwpWtwJgWrhcsFMMfFFhFp
|
||||
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
|
||||
PmmdzqPrVvPwwTWBwg
|
||||
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
|
||||
ttgJtRGJQctTZtZT
|
||||
CrZsJsPPZsGzwwsLwLmpwMDw";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(&parse(EXAMPLE)), 157);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(&parse(EXAMPLE)), 70);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
|
||||
struct Pair([RangeInclusive<u64>; 2]);
|
||||
|
||||
impl From<&str> for Pair {
|
||||
fn from(value: &str) -> Self {
|
||||
let ranges = value.split_once(',').unwrap();
|
||||
Pair([parse_range(ranges.0), parse_range(ranges.1)])
|
||||
}
|
||||
}
|
||||
|
||||
impl Pair {
|
||||
fn fully_contained(&self) -> bool {
|
||||
(self.0[0].start() <= self.0[1].start() && self.0[0].end() >= self.0[1].end())
|
||||
|| (self.0[1].start() <= self.0[0].start() && self.0[1].end() >= self.0[0].end())
|
||||
}
|
||||
fn overlaps(&self) -> bool {
|
||||
self.0[0].contains(self.0[1].start())
|
||||
|| self.0[0].contains(self.0[1].end())
|
||||
|| self.0[1].contains(self.0[0].start())
|
||||
|| self.0[1].contains(self.0[0].end())
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_range(s: &str) -> RangeInclusive<u64> {
|
||||
let (lower, upper) = s.split_once('-').unwrap();
|
||||
RangeInclusive::new(lower.parse().unwrap(), upper.parse().unwrap())
|
||||
}
|
||||
|
||||
#[aoc_generator(day4)]
|
||||
fn parse(input: &str) -> Vec<Pair> {
|
||||
input.lines().map(|l| l.into()).collect()
|
||||
}
|
||||
|
||||
#[aoc(day4, part1)]
|
||||
fn part1(input: &[Pair]) -> u64 {
|
||||
input.iter().filter(|p| p.fully_contained()).count() as u64
|
||||
}
|
||||
|
||||
#[aoc(day4, part2)]
|
||||
fn part2(input: &[Pair]) -> u64 {
|
||||
input.iter().filter(|p| p.overlaps()).count() as u64
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "2-4,6-8
|
||||
2-3,4-5
|
||||
5-7,7-9
|
||||
2-8,3-7
|
||||
6-6,4-6
|
||||
2-6,4-8";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(&parse(EXAMPLE)), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(&parse(EXAMPLE)), 4);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use itertools::Itertools;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Instruction {
|
||||
n: usize,
|
||||
from: usize,
|
||||
to: usize,
|
||||
}
|
||||
|
||||
fn run_machine(stacks: &mut Vec<VecDeque<u8>>, instructions: &Vec<Instruction>) {
|
||||
for inst in instructions {
|
||||
for _ in 0..inst.n {
|
||||
let moving = stacks[inst.from].pop_front().unwrap();
|
||||
stacks[inst.to].push_front(moving);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_machine2(stacks: &mut Vec<VecDeque<u8>>, instructions: &Vec<Instruction>) {
|
||||
for inst in instructions {
|
||||
let mut moving = stacks[inst.from].split_off(inst.n);
|
||||
// semantics of split_off are opposite of what we want
|
||||
std::mem::swap(&mut moving, &mut stacks[inst.from]);
|
||||
moving.append(&mut stacks[inst.to]);
|
||||
stacks[inst.to] = moving;
|
||||
}
|
||||
}
|
||||
|
||||
#[aoc_generator(day5)]
|
||||
fn parse(input: &str) -> (Vec<VecDeque<u8>>, Vec<Instruction>) {
|
||||
enum State {
|
||||
Stacks,
|
||||
Ids,
|
||||
Instructions,
|
||||
}
|
||||
let mut stacks = HashMap::new();
|
||||
let mut instructions = Vec::new();
|
||||
let mut state = State::Stacks;
|
||||
for line in input.lines() {
|
||||
match state {
|
||||
State::Stacks => {
|
||||
for (stack, top) in line.as_bytes().chunks(4).into_iter().map(|s| s[1]).enumerate() {
|
||||
if top.is_ascii_digit() {
|
||||
state = State::Ids
|
||||
} else if top != b' ' {
|
||||
stacks.entry(stack).or_insert(VecDeque::new()).push_back(top);
|
||||
}
|
||||
}
|
||||
}
|
||||
State::Ids => {
|
||||
if line == "" {
|
||||
state = State::Instructions
|
||||
}
|
||||
}
|
||||
State::Instructions => {
|
||||
let tokens = line.split_ascii_whitespace().collect_vec();
|
||||
|
||||
instructions.push(Instruction {
|
||||
n: tokens[1].parse::<usize>().unwrap(),
|
||||
from: tokens[3].parse::<usize>().unwrap() - 1,
|
||||
to: tokens[5].parse::<usize>().unwrap() - 1,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
(
|
||||
stacks
|
||||
.iter()
|
||||
.sorted_by_key(|(k, _v)| **k)
|
||||
.map(|(_k, v)| v.clone())
|
||||
.collect_vec(),
|
||||
instructions,
|
||||
)
|
||||
}
|
||||
|
||||
#[aoc(day5, part1)]
|
||||
fn part1((stacks, instructions): &(Vec<VecDeque<u8>>, Vec<Instruction>)) -> String {
|
||||
let mut stacks = stacks.clone();
|
||||
run_machine(&mut stacks, &instructions);
|
||||
stacks.iter().map(|s| *s.front().unwrap() as char).join("")
|
||||
}
|
||||
|
||||
#[aoc(day5, part2)]
|
||||
fn part2((stacks, instructions): &(Vec<VecDeque<u8>>, Vec<Instruction>)) -> String {
|
||||
let mut stacks = stacks.clone();
|
||||
run_machine2(&mut stacks, &instructions);
|
||||
stacks.iter().map(|s| *s.front().unwrap() as char).join("")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
const EXAMPLE: &str = " [D]
|
||||
[N] [C]
|
||||
[Z] [M] [P]
|
||||
1 2 3
|
||||
|
||||
move 1 from 2 to 1
|
||||
move 3 from 1 to 3
|
||||
move 2 from 2 to 1
|
||||
move 1 from 1 to 2";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(&parse(EXAMPLE)), "CMZ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(&parse(EXAMPLE)), "MCD");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
use aoc_runner_derive::aoc;
|
||||
use itertools::Itertools;
|
||||
use std::io::BufRead;
|
||||
|
||||
// PROBLEM 1 solution
|
||||
#[aoc(day6, part1)]
|
||||
fn part1(input: &[u8]) -> u64 {
|
||||
let s = input.lines().next().unwrap().unwrap();
|
||||
s.as_bytes()
|
||||
.windows(4)
|
||||
.enumerate()
|
||||
.find_map(|(i, window)| {
|
||||
if window[1..4].iter().all(|c| *c != window[0])
|
||||
&& window[2..4].iter().all(|c| *c != window[1])
|
||||
&& window[2] != window[3]
|
||||
{
|
||||
println!(
|
||||
"Unique window: {:?} at {}",
|
||||
window.iter().map(|c| *c as char).collect_vec(),
|
||||
i
|
||||
);
|
||||
Some(i + 4)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.unwrap() as u64
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
#[aoc(day6, part2)]
|
||||
fn part2(input: &[u8]) -> u64 {
|
||||
let s = input.lines().next().unwrap().unwrap();
|
||||
let size = 14;
|
||||
s.as_bytes()
|
||||
.windows(size)
|
||||
.enumerate()
|
||||
.find_map(|(i, window)| {
|
||||
for i in 1..size {
|
||||
let shifted = &window[i..];
|
||||
if shifted.iter().enumerate().any(|(j, c)| *c == window[j]) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(i + 14)
|
||||
})
|
||||
.unwrap() as u64
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::day6::*;
|
||||
|
||||
const EXAMPLE1: &[u8] = b"bvwbjplbgvbhsrlpgdmjqwftvncz";
|
||||
const EXAMPLE2: &[u8] = b"nppdvjthqldpwncqszvftbrmjlhg";
|
||||
const EXAMPLE3: &[u8] = b"nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg";
|
||||
const EXAMPLE4: &[u8] = b"zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(EXAMPLE1), 5);
|
||||
assert_eq!(part1(EXAMPLE2), 6);
|
||||
assert_eq!(part1(EXAMPLE3), 10);
|
||||
assert_eq!(part1(EXAMPLE4), 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(EXAMPLE1), 23);
|
||||
assert_eq!(part2(EXAMPLE2), 23);
|
||||
assert_eq!(part2(EXAMPLE3), 29);
|
||||
assert_eq!(part2(EXAMPLE4), 26);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use itertools::Itertools;
|
||||
|
||||
#[derive(Debug)]
|
||||
enum DirEntry {
|
||||
Directory,
|
||||
File(u64),
|
||||
}
|
||||
|
||||
type Filesystem = HashMap<String, HashMap<String, DirEntry>>;
|
||||
|
||||
fn new_cwd(old_cwd: &str, target: &str) -> String {
|
||||
match target {
|
||||
"/" => "/".to_owned(),
|
||||
".." => {
|
||||
let mut tokens = old_cwd.split('/').collect_vec();
|
||||
tokens.pop();
|
||||
tokens.pop();
|
||||
tokens.join("/") + "/"
|
||||
}
|
||||
s => old_cwd.to_owned() + s + "/",
|
||||
}
|
||||
}
|
||||
|
||||
fn dir_usage(fs: &Filesystem, path: &str) -> u64 {
|
||||
fs.iter()
|
||||
.filter(|(k, _v)| k.starts_with(path))
|
||||
.map(|(_k, v)| {
|
||||
v.values()
|
||||
.map(|v| match v {
|
||||
DirEntry::File(n) => *n,
|
||||
_ => 0,
|
||||
})
|
||||
.sum::<u64>()
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
#[aoc_generator(day7)]
|
||||
fn parse(input: &str) -> Filesystem {
|
||||
let mut cwd = "/".to_owned();
|
||||
let mut fs = Filesystem::new();
|
||||
let mut lines = input.lines();
|
||||
|
||||
while let Some(line) = lines.next() {
|
||||
let tokens = line.split_ascii_whitespace().collect_vec();
|
||||
if tokens[0] == "$" {
|
||||
// command
|
||||
match tokens[1] {
|
||||
"cd" => {
|
||||
cwd = new_cwd(&cwd, tokens[2]);
|
||||
fs.entry(cwd.to_owned()).or_insert(HashMap::new());
|
||||
}
|
||||
"ls" => {}
|
||||
s => {
|
||||
panic!("invalid command `{s}`")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// file entry
|
||||
if let Ok(size) = tokens[0].parse() {
|
||||
fs.entry(cwd.to_owned()).and_modify(|e| {
|
||||
e.insert(tokens[1].into(), DirEntry::File(size));
|
||||
});
|
||||
}
|
||||
// dir entry
|
||||
else {
|
||||
fs.entry(cwd.to_owned() + tokens[1] + "/").or_insert(HashMap::new());
|
||||
fs.entry(cwd.to_owned()).and_modify(|e| {
|
||||
e.insert(tokens[1].into(), DirEntry::Directory);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fs
|
||||
}
|
||||
|
||||
const AVAIL_DISK: u64 = 70000000;
|
||||
const MIN_FREE: u64 = 30000000;
|
||||
|
||||
#[aoc(day7, part1)]
|
||||
fn part1(fs: &Filesystem) -> u64 {
|
||||
fs.keys()
|
||||
.map(|path| dir_usage(&fs, path))
|
||||
.filter(|v| *v <= 100000)
|
||||
.sum()
|
||||
}
|
||||
|
||||
#[aoc(day7, part2)]
|
||||
fn part2(fs: &Filesystem) -> u64 {
|
||||
let mut usages = fs.keys().map(|path| dir_usage(&fs, path)).sorted().collect_vec();
|
||||
|
||||
let total_usage = usages.pop().unwrap(); // sorted list, largest dir will always be the root which can't be deleted
|
||||
let need_to_free_at_least = MIN_FREE - (AVAIL_DISK - total_usage);
|
||||
|
||||
*usages.iter().find(|s| **s >= need_to_free_at_least).unwrap()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "$ cd /
|
||||
$ ls
|
||||
dir a
|
||||
14848514 b.txt
|
||||
8504156 c.dat
|
||||
dir d
|
||||
$ cd a
|
||||
$ ls
|
||||
dir e
|
||||
29116 f
|
||||
2557 g
|
||||
62596 h.lst
|
||||
$ cd e
|
||||
$ ls
|
||||
584 i
|
||||
$ cd ..
|
||||
$ cd ..
|
||||
$ cd d
|
||||
$ ls
|
||||
4060174 j
|
||||
8033020 d.log
|
||||
5626152 d.ext
|
||||
7214296 k";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(&parse(EXAMPLE)), 95437);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(&parse(EXAMPLE)), 24933642);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
mod day5;
|
||||
mod day7;
|
||||
mod day4;
|
||||
mod day1;
|
||||
mod day2;
|
||||
mod day3;
|
||||
use aoc_runner_derive::aoc_lib;
|
||||
|
||||
mod day6;
|
||||
|
||||
aoc_lib! { year = 2022 }
|
||||
@@ -0,0 +1,3 @@
|
||||
use aoc_runner_derive::aoc_main;
|
||||
|
||||
aoc_main! { lib = aoc2022 }
|
||||
Reference in new issue
Block a user