2023: convert to aoc-runner
This commit is contained in:
107 files changed
+1563
-12181
No files matched your search
@@ -0,0 +1,72 @@
|
||||
use aoc_runner_derive::aoc;
|
||||
|
||||
// PROBLEM1 solution
|
||||
fn problem1_lineval(line: &str) -> u64 {
|
||||
// forward iterate to find the first numeric value
|
||||
let first = line.chars().find(|c| c.is_digit(10)).unwrap();
|
||||
let last = line.chars().rev().find(|c| c.is_digit(10)).unwrap();
|
||||
|
||||
(first.to_digit(10).unwrap() * 10 + last.to_digit(10).unwrap()).into()
|
||||
}
|
||||
|
||||
#[aoc(day1, part1)]
|
||||
fn part1(input: &str) -> u64 {
|
||||
input.lines().map(problem1_lineval).sum()
|
||||
}
|
||||
|
||||
// PROBLEM2 solution
|
||||
const DIGITS: &[(&str, u64)] = &[
|
||||
("one", 1),
|
||||
("two", 2),
|
||||
("three", 3),
|
||||
("four", 4),
|
||||
("five", 5),
|
||||
("six", 6),
|
||||
("seven", 7),
|
||||
("eight", 8),
|
||||
("nine", 9),
|
||||
];
|
||||
|
||||
fn problem2_numeric(start: &str) -> Option<u64> {
|
||||
let char = start.chars().nth(0).unwrap();
|
||||
if char.is_numeric() {
|
||||
Some(char.to_digit(10).unwrap().into())
|
||||
} else {
|
||||
for (s, n) in DIGITS {
|
||||
if start.starts_with(s) {
|
||||
return Some(*n);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn problem2_lineval(line: &str) -> u64 {
|
||||
let mut first = None;
|
||||
for pos in 0..line.len() {
|
||||
let (_, sub) = line.split_at(pos);
|
||||
if let Some(n) = problem2_numeric(sub) {
|
||||
first = Some(n);
|
||||
break;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let mut second = None;
|
||||
for pos in (0..line.len()).rev() {
|
||||
let (_, sub) = line.split_at(pos);
|
||||
if let Some(n) = problem2_numeric(sub) {
|
||||
second = Some(n);
|
||||
break;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
first.unwrap() * 10 + second.unwrap()
|
||||
}
|
||||
|
||||
#[aoc(day1, part2)]
|
||||
fn part2(input: &str) -> u64 {
|
||||
input.lines().map(problem2_lineval).sum()
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
use aoc_runner_derive::aoc;
|
||||
|
||||
// PARSE
|
||||
|
||||
#[derive(Debug)]
|
||||
struct MapCell {
|
||||
dist: u64,
|
||||
kind: char,
|
||||
inside: bool,
|
||||
}
|
||||
|
||||
impl From<char> for MapCell {
|
||||
fn from(c: char) -> Self {
|
||||
MapCell {
|
||||
dist: 0,
|
||||
kind: c,
|
||||
inside: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct PipeMap {
|
||||
map: Vec<Vec<MapCell>>,
|
||||
start: (usize, usize),
|
||||
}
|
||||
|
||||
const ALL_ADJ: [(isize, isize); 8] = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)];
|
||||
|
||||
impl PipeMap {
|
||||
fn adjacencies(c: char) -> Option<[(isize, isize); 2]> {
|
||||
match c {
|
||||
'|' => Some([(0, -1), (0, 1)]),
|
||||
'-' => Some([(-1, 0), (1, 0)]),
|
||||
'L' => Some([(0, -1), (1, 0)]),
|
||||
'J' => Some([(0, -1), (-1, 0)]),
|
||||
'7' => Some([(0, 1), (-1, 0)]),
|
||||
'F' => Some([(0, 1), (1, 0)]),
|
||||
'.' => None,
|
||||
'S' => None,
|
||||
_ => panic!("unhandled type"),
|
||||
}
|
||||
}
|
||||
fn valid_pos(&self, pos: (isize, isize)) -> bool {
|
||||
pos.0 >= 0 && pos.0 < self.map[0].len() as isize && pos.1 >= 0 && pos.1 < self.map.len() as isize
|
||||
}
|
||||
|
||||
fn apply_adj(&self, pos: (usize, usize), adj: (isize, isize)) -> Option<(usize, usize)> {
|
||||
if self.valid_pos((pos.0 as isize + adj.0, pos.1 as isize + adj.1)) {
|
||||
Some(((pos.0 as isize + adj.0) as usize, (pos.1 as isize + adj.1) as usize))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn adjacent_positions(&self, pos: (usize, usize)) -> Option<[(usize, usize); 2]> {
|
||||
let adj = Self::adjacencies(self.map[pos.1][pos.0].kind);
|
||||
if let Some(adj) = adj {
|
||||
let mut positions = adj.iter().filter_map(|adj| self.apply_adj(pos, *adj));
|
||||
Some([positions.next().unwrap(), positions.next().unwrap()])
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn start_adjacencies(&self) -> [(usize, usize); 2] {
|
||||
let mut adj_positions = Vec::new();
|
||||
for neighbour in ALL_ADJ.iter().filter_map(|adj| self.apply_adj(self.start, *adj)) {
|
||||
if let Some(neigh_adjs) = self.adjacent_positions(neighbour) {
|
||||
if neigh_adjs.contains(&self.start) {
|
||||
adj_positions.push(neighbour)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[adj_positions[0], adj_positions[1]]
|
||||
}
|
||||
|
||||
fn mark_inside(&mut self) {
|
||||
let start_adj = self.start_adjacencies();
|
||||
|
||||
let start_kind = if start_adj.contains(&self.apply_adj(self.start, (0, -1)).unwrap_or((99999, 99999)))
|
||||
&& start_adj.contains(&self.apply_adj(self.start, (0, 1)).unwrap_or((99999, 99999)))
|
||||
{
|
||||
'|'
|
||||
} else if start_adj.contains(&self.apply_adj(self.start, (-1, 0)).unwrap_or((99999, 99999)))
|
||||
&& start_adj.contains(&self.apply_adj(self.start, (1, 0)).unwrap_or((99999, 99999)))
|
||||
{
|
||||
'-'
|
||||
} else if start_adj.contains(&self.apply_adj(self.start, (0, -1)).unwrap_or((99999, 99999)))
|
||||
&& start_adj.contains(&self.apply_adj(self.start, (1, 0)).unwrap_or((99999, 99999)))
|
||||
{
|
||||
'L'
|
||||
} else if start_adj.contains(&self.apply_adj(self.start, (0, -1)).unwrap_or((99999, 99999)))
|
||||
&& start_adj.contains(&self.apply_adj(self.start, (-1, 0)).unwrap_or((99999, 99999)))
|
||||
{
|
||||
'J'
|
||||
} else if start_adj.contains(&self.apply_adj(self.start, (0, 1)).unwrap_or((99999, 99999)))
|
||||
&& start_adj.contains(&self.apply_adj(self.start, (-1, 0)).unwrap_or((99999, 99999)))
|
||||
{
|
||||
'7'
|
||||
} else if start_adj.contains(&self.apply_adj(self.start, (0, 1)).unwrap_or((99999, 99999)))
|
||||
&& start_adj.contains(&self.apply_adj(self.start, (1, 0)).unwrap_or((99999, 99999)))
|
||||
{
|
||||
'F'
|
||||
} else {
|
||||
panic!("invalid start");
|
||||
};
|
||||
|
||||
for row in &mut self.map {
|
||||
let mut inside = false;
|
||||
for cell in row {
|
||||
let mut kind = cell.kind;
|
||||
if cell.dist == 0 && kind != 'S' {
|
||||
cell.inside = inside;
|
||||
} else {
|
||||
if kind == 'S' {
|
||||
kind = start_kind;
|
||||
}
|
||||
if kind == '|' || kind == 'L' || kind == 'J' {
|
||||
inside = !inside;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for PipeMap {
|
||||
fn from(input: &str) -> Self {
|
||||
let mut map: Vec<Vec<MapCell>> = Vec::new();
|
||||
for line in input.lines() {
|
||||
map.push(line.chars().map(MapCell::from).collect());
|
||||
}
|
||||
|
||||
let start = map
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(idx, row)| (row.iter().position(|p| p.kind == 'S'), idx))
|
||||
.find(|(x, _)| x.is_some())
|
||||
.unwrap();
|
||||
let start = (start.0.unwrap(), start.1);
|
||||
|
||||
let mut pipemap = PipeMap { map, start };
|
||||
|
||||
let mut cur_positions = pipemap.start_adjacencies();
|
||||
let mut cur_distance = 1;
|
||||
loop {
|
||||
for pos in cur_positions {
|
||||
pipemap.map[pos.1][pos.0].dist = cur_distance;
|
||||
}
|
||||
cur_distance += 1;
|
||||
|
||||
if let Some(new_pos1) = pipemap.adjacent_positions(cur_positions[0]) {
|
||||
if let Some(new_pos1) = new_pos1
|
||||
.iter()
|
||||
.find(|pos| pipemap.map[pos.1][pos.0].dist == 0 && pipemap.map[pos.1][pos.0].kind != 'S')
|
||||
{
|
||||
cur_positions[0] = *new_pos1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if let Some(new_pos2) = pipemap.adjacent_positions(cur_positions[1]) {
|
||||
if let Some(new_pos2) = new_pos2
|
||||
.iter()
|
||||
.find(|pos| pipemap.map[pos.1][pos.0].dist == 0 && pipemap.map[pos.1][pos.0].kind != 'S')
|
||||
{
|
||||
cur_positions[1] = *new_pos2;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if cur_positions[0] == cur_positions[1] {
|
||||
pipemap.map[cur_positions[0].1][cur_positions[0].0].dist = cur_distance;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
pipemap
|
||||
}
|
||||
}
|
||||
|
||||
// PROBLEM 1 solution
|
||||
|
||||
#[aoc(day10, part1)]
|
||||
fn part1(input: &str) -> u64 {
|
||||
let map = PipeMap::from(input);
|
||||
|
||||
map.map
|
||||
.iter()
|
||||
.map(|row| row.iter().map(|cell| cell.dist).max().unwrap())
|
||||
.max()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
#[aoc(day10, part2)]
|
||||
fn part2(input: &str) -> u64 {
|
||||
let mut map = PipeMap::from(input);
|
||||
map.mark_inside();
|
||||
|
||||
// for row in &map.map {
|
||||
// for cell in row {
|
||||
// print!("{}", cell.kind);
|
||||
// }
|
||||
// print!(" ");
|
||||
// for cell in row {
|
||||
// print!(
|
||||
// "{}",
|
||||
// match cell.inside {
|
||||
// true => 'I',
|
||||
// false => 'O',
|
||||
// }
|
||||
// );
|
||||
// }
|
||||
// println!();
|
||||
// }
|
||||
|
||||
map.map
|
||||
.iter()
|
||||
.map(|row| row.iter().filter(|cell| cell.inside).count())
|
||||
.sum::<usize>() as u64
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "..F7.
|
||||
.FJ|.
|
||||
SJ.L7
|
||||
|F--J
|
||||
LJ...";
|
||||
|
||||
const EXAMPLE2: &str = "FF7FSF7F7F7F7F7F---7
|
||||
L|LJ||||||||||||F--J
|
||||
FL-7LJLJ||||||LJL-77
|
||||
F--JF--7||LJLJ7F7FJ-
|
||||
L---JF-JLJ.||-FJLJJ7
|
||||
|F|F-JF---7F7-L7L|7|
|
||||
|FFJF7L7F-JF7|JL---7
|
||||
7-L-JL7||F7|L7F-7F7|
|
||||
L.L7LFJ|||||FJL7||LJ
|
||||
L7JLJL-JLJLJL--JLJ.L";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(EXAMPLE), 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(EXAMPLE2), 10);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
use aoc_runner_derive::aoc;
|
||||
use std::fmt::{Display, Write};
|
||||
use std::iter::repeat;
|
||||
|
||||
// PARSE
|
||||
|
||||
struct GalaxyMap {
|
||||
map: Vec<Vec<char>>,
|
||||
galaxy_positions: Vec<(usize, usize)>,
|
||||
}
|
||||
|
||||
impl From<&str> for GalaxyMap {
|
||||
fn from(input: &str) -> Self {
|
||||
let map = GalaxyMap {
|
||||
map: input.lines().map(|line| line.chars().collect()).collect(),
|
||||
galaxy_positions: Vec::new(),
|
||||
};
|
||||
map
|
||||
}
|
||||
}
|
||||
|
||||
impl GalaxyMap {
|
||||
fn universe_expansion(&mut self) {
|
||||
let mut columns_to_insert = Vec::new();
|
||||
|
||||
for col in 0..self.map[0].len() {
|
||||
if self.map.iter().map(|row| row[col]).all(|c| c != '#') {
|
||||
columns_to_insert.push(col);
|
||||
}
|
||||
}
|
||||
|
||||
for row in &mut self.map {
|
||||
let mut offset = 0;
|
||||
for col in &columns_to_insert {
|
||||
row.insert(*col + offset, '.');
|
||||
offset += 1;
|
||||
}
|
||||
}
|
||||
|
||||
let rows_to_insert: Vec<_> = self
|
||||
.map
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(idx, row)| if !row.contains(&'#') { Some(idx) } else { None })
|
||||
.collect();
|
||||
let gen_row: Vec<_> = repeat('.').take(self.map[0].len()).collect();
|
||||
let mut offset = 0;
|
||||
for idx in rows_to_insert {
|
||||
self.map.insert(idx + offset, gen_row.clone());
|
||||
offset += 1;
|
||||
}
|
||||
}
|
||||
fn universe_expansion2(&mut self) {
|
||||
let mut columns_to_grow = Vec::new();
|
||||
|
||||
for col in 0..self.map[0].len() {
|
||||
if self.map.iter().map(|row| row[col]).all(|c| c != '#') {
|
||||
columns_to_grow.push(col);
|
||||
}
|
||||
}
|
||||
|
||||
for row in &mut self.map {
|
||||
for col in &columns_to_grow {
|
||||
row[*col] = 'x';
|
||||
}
|
||||
}
|
||||
|
||||
let rows_to_grow: Vec<_> = self
|
||||
.map
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(idx, row)| if !row.contains(&'#') { Some(idx) } else { None })
|
||||
.collect();
|
||||
let gen_row: Vec<_> = repeat('x').take(self.map[0].len()).collect();
|
||||
for idx in rows_to_grow {
|
||||
self.map[idx] = gen_row.clone();
|
||||
}
|
||||
}
|
||||
fn find_galaxies(&mut self) {
|
||||
for (y, row) in self.map.iter().enumerate() {
|
||||
for (x, _c) in row.iter().enumerate().filter(|(_x, c)| **c == '#') {
|
||||
self.galaxy_positions.push((x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn galaxy_distance(&self, a: usize, b: usize) -> u64 {
|
||||
let (a_x, a_y) = self.galaxy_positions[a];
|
||||
let (b_x, b_y) = self.galaxy_positions[b];
|
||||
|
||||
let x_dist = b_x.abs_diff(a_x);
|
||||
let y_dist = b_y.abs_diff(a_y);
|
||||
|
||||
x_dist as u64 + y_dist as u64
|
||||
}
|
||||
fn galaxy_distance2(&self, a: usize, b: usize) -> u64 {
|
||||
let (a_x, a_y) = self.galaxy_positions[a];
|
||||
let (b_x, b_y) = self.galaxy_positions[b];
|
||||
let x_dist = b_x.abs_diff(a_x);
|
||||
let y_dist = b_y.abs_diff(a_y);
|
||||
|
||||
let mut dist = x_dist as u64 + y_dist as u64;
|
||||
|
||||
for row in a_y.min(b_y)..a_y.max(b_y) {
|
||||
if self.map[row].iter().all(|c| *c == 'x') {
|
||||
dist += 1000000 - 1;
|
||||
}
|
||||
}
|
||||
|
||||
for col in a_x.min(b_x)..a_x.max(b_x) {
|
||||
if self.map.iter().all(|row| row[col] == 'x') {
|
||||
dist += 1000000 - 1;
|
||||
}
|
||||
}
|
||||
|
||||
dist
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for GalaxyMap {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
for row in &self.map {
|
||||
for c in row {
|
||||
f.write_char(*c)?;
|
||||
}
|
||||
f.write_char('\n')?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// PROBLEM 1 solution
|
||||
|
||||
#[aoc(day11, part1)]
|
||||
fn part1(input: &str) -> u64 {
|
||||
let mut map = GalaxyMap::from(input);
|
||||
map.universe_expansion();
|
||||
map.find_galaxies();
|
||||
// println!("{}", map);
|
||||
|
||||
let mut galaxies: Vec<_> = (0..map.galaxy_positions.len()).collect();
|
||||
let mut sum = 0u64;
|
||||
while let Some(target) = galaxies.pop() {
|
||||
sum += galaxies
|
||||
.iter()
|
||||
.map(|source| map.galaxy_distance(*source, target))
|
||||
.sum::<u64>();
|
||||
}
|
||||
sum
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
#[aoc(day11, part2)]
|
||||
fn part2(input: &str) -> u64 {
|
||||
let mut map = GalaxyMap::from(input);
|
||||
map.universe_expansion2();
|
||||
map.find_galaxies();
|
||||
// println!("{}", map);
|
||||
|
||||
let mut galaxies: Vec<_> = (0..map.galaxy_positions.len()).collect();
|
||||
let mut sum = 0u64;
|
||||
while let Some(target) = galaxies.pop() {
|
||||
sum += galaxies
|
||||
.iter()
|
||||
.map(|source| map.galaxy_distance2(*source, target))
|
||||
.sum::<u64>();
|
||||
}
|
||||
sum
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "...#......
|
||||
.......#..
|
||||
#.........
|
||||
..........
|
||||
......#...
|
||||
.#........
|
||||
.........#
|
||||
..........
|
||||
.......#..
|
||||
#...#.....";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(EXAMPLE), 374);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(EXAMPLE), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
use aoc_runner_derive::aoc;
|
||||
use itertools::Itertools;
|
||||
use rayon::prelude::*;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
|
||||
// PARSE
|
||||
|
||||
#[derive(Debug)]
|
||||
struct SpringRow<'a> {
|
||||
springs: Vec<char>,
|
||||
spans: Vec<usize>,
|
||||
cache: RefCell<HashMap<(usize, &'a [usize], usize), u64>>,
|
||||
}
|
||||
|
||||
impl<'a> From<&str> for SpringRow<'a> {
|
||||
fn from(s: &str) -> Self {
|
||||
let (springs_s, spans_s) = s.split_once(' ').unwrap();
|
||||
SpringRow {
|
||||
springs: springs_s.chars().collect(),
|
||||
spans: spans_s.split(',').map(|x| x.parse().unwrap()).collect(),
|
||||
cache: RefCell::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> SpringRow<'a> {
|
||||
fn possible_arrangements(&self) -> u64 {
|
||||
let mut permutations = vec![self.springs.clone()];
|
||||
while let Some(cur) = permutations.iter().position(|perm| perm.contains(&'?')) {
|
||||
let perm = permutations.remove(cur);
|
||||
let rep_pos = perm.iter().position(|c| *c == '?').unwrap();
|
||||
|
||||
let mut new_elem = perm.clone();
|
||||
|
||||
new_elem[rep_pos] = '.';
|
||||
permutations.push(new_elem.clone());
|
||||
new_elem[rep_pos] = '#';
|
||||
permutations.push(new_elem);
|
||||
}
|
||||
|
||||
permutations
|
||||
.iter()
|
||||
.filter_map(|perm| {
|
||||
let groups: Vec<usize> = perm
|
||||
.iter()
|
||||
.group_by(|c| **c == '#')
|
||||
.into_iter()
|
||||
.filter_map(|(key, group)| if key { Some(group.count()) } else { None })
|
||||
.collect();
|
||||
if groups == self.spans {
|
||||
Some(())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.count() as u64
|
||||
}
|
||||
fn memoize_arrangements_r(&self, idx: usize, spans_left: &'a [usize], cur_span_left: usize) -> u64 {
|
||||
if let Some(value) = self.cache.borrow().get(&(idx, spans_left, cur_span_left)) {
|
||||
return *value;
|
||||
}
|
||||
let result = self.possible_arrangements_r(idx, spans_left, cur_span_left);
|
||||
self.cache.borrow_mut().insert((idx, spans_left, cur_span_left), result);
|
||||
result
|
||||
}
|
||||
fn possible_arrangements_r(&self, idx: usize, spans_left: &'a [usize], cur_span_left: usize) -> u64 {
|
||||
if cur_span_left == 0 && spans_left.len() == 1 {
|
||||
// everything is consumed. if we're at the end, we good
|
||||
// if we have stuff left, as long as it doesn't contain a fixed broken spring we good
|
||||
if idx == self.springs.len() || !self.springs[idx..].contains(&'#') {
|
||||
// println!("{:?} valid", self.springs);
|
||||
return 1;
|
||||
}
|
||||
// something invalid
|
||||
return 0;
|
||||
}
|
||||
if idx >= self.springs.len() {
|
||||
// reached the end of the string without consuming all our spans
|
||||
// println!(
|
||||
// "{:?} invalid idx: {} spans_left: {:?}",
|
||||
// self.springs, idx, spans_left
|
||||
// );
|
||||
return 0;
|
||||
}
|
||||
// println!(
|
||||
// "call idx: {} str: {:?} spans_left: {:?} cur_span_left: {}",
|
||||
// idx,
|
||||
// &self.springs[idx..],
|
||||
// spans_left,
|
||||
// cur_span_left
|
||||
// );
|
||||
return if cur_span_left == 0 {
|
||||
match self.springs[idx] {
|
||||
'#' => 0, // a broken spring after we have completed our span is invalid
|
||||
// a space or a ? (becomes a space) starts a new span
|
||||
'.' | '?' => self.memoize_arrangements_r(idx + 1, &spans_left[1..], spans_left[1]),
|
||||
_ => panic!("invalid spring"),
|
||||
}
|
||||
} else {
|
||||
// we are mid span
|
||||
match self.springs[idx] {
|
||||
// cur_span_left != 0, so we still have work to do with broken springs
|
||||
'#' => self.memoize_arrangements_r(idx + 1, spans_left, cur_span_left - 1),
|
||||
'.' => {
|
||||
if spans_left[0] == cur_span_left {
|
||||
self.memoize_arrangements_r(idx + 1, spans_left, cur_span_left)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
'?' => {
|
||||
if spans_left[0] == cur_span_left {
|
||||
self.memoize_arrangements_r(idx + 1, spans_left, cur_span_left - 1)
|
||||
+ self.memoize_arrangements_r(idx + 1, spans_left, cur_span_left)
|
||||
} else {
|
||||
self.memoize_arrangements_r(idx + 1, spans_left, cur_span_left - 1)
|
||||
}
|
||||
}
|
||||
_ => panic!("invalid spring"),
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// PROBLEM 1 solution
|
||||
|
||||
#[aoc(day12, part1)]
|
||||
fn part1(input: &str) -> u64 {
|
||||
let rows: Vec<SpringRow> = input.lines().map(|row| SpringRow::from(row)).collect();
|
||||
|
||||
rows.iter()
|
||||
.map(|row| row.possible_arrangements_r(0, &row.spans, row.spans[0]))
|
||||
.sum()
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
#[aoc(day12, part2)]
|
||||
fn part2(input: &str) -> u64 {
|
||||
let mut rows: Vec<SpringRow> = input.lines().map(|row| SpringRow::from(row)).collect();
|
||||
|
||||
for row in &mut rows {
|
||||
let orig_slice = &row.springs.clone();
|
||||
for _i in 0..4 {
|
||||
row.springs.push('?');
|
||||
row.springs.extend_from_slice(orig_slice);
|
||||
}
|
||||
|
||||
let orig_span_slice = &row.spans.clone();
|
||||
for _i in 0..4 {
|
||||
row.spans.extend_from_slice(orig_span_slice);
|
||||
}
|
||||
}
|
||||
rows.iter()
|
||||
.map(|row| row.possible_arrangements_r(0, &row.spans, row.spans[0]))
|
||||
.sum()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "???.### 1,1,3
|
||||
.??..??...?##. 1,1,3
|
||||
?#?#?#?#?#?#?#? 1,3,1,6
|
||||
????.#...#... 4,1,1
|
||||
????.######..#####. 1,6,5
|
||||
?###???????? 3,2,1";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(EXAMPLE), 21);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(EXAMPLE), 525152);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use std::ops::Index;
|
||||
|
||||
// PARSE
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Pattern {
|
||||
mirrors: Vec<Vec<char>>,
|
||||
}
|
||||
|
||||
impl Pattern {
|
||||
fn width(&self) -> usize {
|
||||
self.mirrors[0].len()
|
||||
}
|
||||
fn height(&self) -> usize {
|
||||
self.mirrors.len()
|
||||
}
|
||||
fn col(&self, idx: usize) -> Vec<char> {
|
||||
self.mirrors.iter().map(|row| row[idx]).collect()
|
||||
}
|
||||
|
||||
fn find_horizontal_reflection(&self) -> Option<usize> {
|
||||
(1..self.height()).find(|idx| self.is_horizontal_reflection(*idx))
|
||||
}
|
||||
|
||||
fn is_horizontal_reflection(&self, idx: usize) -> bool {
|
||||
let row_pairs = std::cmp::min(idx, self.height() - idx);
|
||||
(0..row_pairs).all(|offset| self.mirrors[idx - offset - 1] == self.mirrors[idx + offset])
|
||||
}
|
||||
|
||||
fn find_vertical_reflection(&self) -> Option<usize> {
|
||||
(1..self.width()).find(|idx| self.is_vertical_reflection(*idx))
|
||||
}
|
||||
|
||||
fn is_vertical_reflection(&self, idx: usize) -> bool {
|
||||
let col_pairs = std::cmp::min(idx, self.width() - idx);
|
||||
(0..col_pairs).all(|offset| self.col(idx - offset - 1) == self.col(idx + offset))
|
||||
}
|
||||
|
||||
fn find_smudged_horizontal_reflection(&self) -> Option<usize> {
|
||||
(1..self.height()).find(|idx| self.is_smudged_horizontal_reflection(*idx))
|
||||
}
|
||||
|
||||
fn is_smudged_horizontal_reflection(&self, idx: usize) -> bool {
|
||||
// Same algorithm for problem 2, but count errors breaking reflection.
|
||||
// If the count == 1 after all checks, then it is our smudge
|
||||
let row_pairs = std::cmp::min(idx, self.height() - idx);
|
||||
(0..row_pairs)
|
||||
.map(|offset| {
|
||||
self.mirrors[idx - offset - 1]
|
||||
.iter()
|
||||
.zip(self.mirrors[idx + offset].iter())
|
||||
.filter(|(a, b)| **a != **b)
|
||||
.count()
|
||||
})
|
||||
.sum::<usize>()
|
||||
== 1
|
||||
}
|
||||
|
||||
fn find_smudged_vertical_reflection(&self) -> Option<usize> {
|
||||
(1..self.width()).find(|idx| self.is_smudged_vertical_reflection(*idx))
|
||||
}
|
||||
|
||||
fn is_smudged_vertical_reflection(&self, idx: usize) -> bool {
|
||||
let col_pairs = std::cmp::min(idx, self.width() - idx);
|
||||
(0..col_pairs)
|
||||
.map(|offset| {
|
||||
self.col(idx - offset - 1)
|
||||
.iter()
|
||||
.zip(self.col(idx + offset).iter())
|
||||
.filter(|(a, b)| **a != **b)
|
||||
.count()
|
||||
})
|
||||
.sum::<usize>()
|
||||
== 1
|
||||
}
|
||||
|
||||
fn reflection_cost(&self) -> u64 {
|
||||
if let Some(refl) = self.find_horizontal_reflection() {
|
||||
100 * refl as u64
|
||||
} else if let Some(refl) = self.find_vertical_reflection() {
|
||||
refl as u64
|
||||
} else {
|
||||
panic!("no reflection");
|
||||
}
|
||||
}
|
||||
|
||||
fn smudged_reflection_cost(&self) -> u64 {
|
||||
if let Some(refl) = self.find_smudged_horizontal_reflection() {
|
||||
100 * refl as u64
|
||||
} else if let Some(refl) = self.find_smudged_vertical_reflection() {
|
||||
refl as u64
|
||||
} else {
|
||||
panic!("no reflection");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Patterns {
|
||||
patterns: Vec<Pattern>,
|
||||
}
|
||||
|
||||
impl From<&str> for Patterns {
|
||||
fn from(input: &str) -> Self {
|
||||
let mut lines = input.lines();
|
||||
let mut patterns = Vec::new();
|
||||
let mut cur_lines = Vec::new();
|
||||
while let Some(line) = lines.next() {
|
||||
if line.len() == 0 {
|
||||
patterns.push(Pattern { mirrors: cur_lines });
|
||||
cur_lines = Vec::new();
|
||||
} else {
|
||||
cur_lines.push(line.chars().collect());
|
||||
}
|
||||
}
|
||||
patterns.push(Pattern { mirrors: cur_lines });
|
||||
Self { patterns }
|
||||
}
|
||||
}
|
||||
|
||||
// PROBLEM 1 solution
|
||||
|
||||
#[aoc_generator(day13)]
|
||||
fn parse(input: &str) -> Patterns {
|
||||
Patterns::from(input)
|
||||
}
|
||||
|
||||
#[aoc(day13, part1)]
|
||||
fn part1(patterns: &Patterns) -> u64 {
|
||||
patterns.patterns.iter().map(|pat| pat.reflection_cost()).sum()
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
#[aoc(day13, part2)]
|
||||
fn part2(patterns: &Patterns) -> u64 {
|
||||
patterns.patterns.iter().map(|pat| pat.smudged_reflection_cost()).sum()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "#.##..##.
|
||||
..#.##.#.
|
||||
##......#
|
||||
##......#
|
||||
..#.##.#.
|
||||
..##..##.
|
||||
#.#.##.#.
|
||||
|
||||
#...##..#
|
||||
#....#..#
|
||||
..##..###
|
||||
#####.##.
|
||||
#####.##.
|
||||
..##..###
|
||||
#....#..#";
|
||||
|
||||
#[test]
|
||||
fn problem1_find_horizontal() {
|
||||
let patterns = Patterns::from(EXAMPLE);
|
||||
assert_eq!(patterns.patterns[1].find_horizontal_reflection(), Some(4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn problem1_find_vertical() {
|
||||
let patterns = Patterns::from(EXAMPLE);
|
||||
assert_eq!(patterns.patterns[0].find_vertical_reflection(), Some(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(&parse(EXAMPLE)), 405);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn problem2_find_horizontal() {
|
||||
let patterns = Patterns::from(EXAMPLE);
|
||||
assert_eq!(patterns.patterns[0].find_smudged_horizontal_reflection(), Some(3));
|
||||
assert_eq!(patterns.patterns[1].find_smudged_horizontal_reflection(), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(&parse(EXAMPLE)), 400);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
use aoc_runner_derive::aoc;
|
||||
use ndarray::*;
|
||||
|
||||
use std::fmt::Display;
|
||||
|
||||
// PARSE
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Platform {
|
||||
matrix: Array2<char>,
|
||||
width: usize,
|
||||
height: usize,
|
||||
}
|
||||
|
||||
impl From<&str> for Platform {
|
||||
fn from(input: &str) -> Self {
|
||||
let rows: Vec<Vec<char>> = input.lines().map(|line| line.chars().collect()).collect();
|
||||
let width = rows[0].len();
|
||||
let height = rows.len();
|
||||
Self {
|
||||
matrix: Array2::from_shape_vec(
|
||||
(height, width),
|
||||
rows.iter().flat_map(|row| row.iter().map(|c| *c)).collect(),
|
||||
)
|
||||
.unwrap(),
|
||||
width,
|
||||
height,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum Axis {
|
||||
Rows,
|
||||
Columns,
|
||||
}
|
||||
|
||||
struct North;
|
||||
struct South;
|
||||
struct East;
|
||||
struct West;
|
||||
|
||||
trait Direction {
|
||||
const REVERSED: bool;
|
||||
const AXIS: Axis;
|
||||
const ROTATIONS: usize;
|
||||
}
|
||||
|
||||
impl Direction for North {
|
||||
const REVERSED: bool = false;
|
||||
const AXIS: Axis = Axis::Columns;
|
||||
const ROTATIONS: usize = 0;
|
||||
}
|
||||
impl Direction for South {
|
||||
const REVERSED: bool = true;
|
||||
const AXIS: Axis = Axis::Columns;
|
||||
const ROTATIONS: usize = 2; // 180
|
||||
}
|
||||
impl Direction for East {
|
||||
const REVERSED: bool = true;
|
||||
const AXIS: Axis = Axis::Rows;
|
||||
const ROTATIONS: usize = 1; // CCW
|
||||
}
|
||||
impl Direction for West {
|
||||
const REVERSED: bool = false;
|
||||
const AXIS: Axis = Axis::Rows;
|
||||
const ROTATIONS: usize = 3; // CW
|
||||
}
|
||||
|
||||
impl<'a> Platform {
|
||||
fn roll<T: Direction>(&mut self) {
|
||||
// Get a view into the rotated matrix with the target direction to the north
|
||||
let mut view = self.matrix.view_mut();
|
||||
|
||||
match T::ROTATIONS % 4 {
|
||||
0 => {}
|
||||
1 => {
|
||||
view.invert_axis(Axis(1));
|
||||
view.swap_axes(0, 1);
|
||||
}
|
||||
2 => {
|
||||
view.invert_axis(Axis(0));
|
||||
view.invert_axis(Axis(1));
|
||||
}
|
||||
3 => {
|
||||
view.swap_axes(0, 1);
|
||||
view.invert_axis(Axis(1));
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
Self::roll_rocks(view);
|
||||
}
|
||||
fn roll_rocks(mut view: ArrayBase<ViewRepr<&mut char>, Dim<[usize; 2]>>) {
|
||||
let axis_len = view.len_of(Axis(1));
|
||||
for mut col in view.columns_mut() {
|
||||
for inner_idx in 1..axis_len {
|
||||
if col[inner_idx] == 'O' {
|
||||
let lower_limit = (0..inner_idx).rev().find(|i| col[*i] == '#').unwrap_or(0);
|
||||
if let Some(empty_pos) = (lower_limit..inner_idx).find(|i| col[*i] == '.') {
|
||||
col.swap(inner_idx, empty_pos);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn score<T: Direction>(&self) -> u64 {
|
||||
match T::AXIS {
|
||||
Axis::Columns => self.score_columns::<T>(),
|
||||
Axis::Rows => self.score_rows::<T>(),
|
||||
}
|
||||
}
|
||||
fn row_or_column_score<T: Direction>(&self, idx: usize) -> usize {
|
||||
if T::REVERSED {
|
||||
idx + 1
|
||||
} else {
|
||||
match T::AXIS {
|
||||
Axis::Rows => self.width - idx,
|
||||
Axis::Columns => self.height - idx,
|
||||
}
|
||||
}
|
||||
}
|
||||
fn score_columns<T: Direction>(&self) -> u64 {
|
||||
self.matrix
|
||||
.rows()
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(idx, row)| row.iter().filter(|c| **c == 'O').count() * self.row_or_column_score::<T>(idx))
|
||||
.sum::<usize>() as u64
|
||||
}
|
||||
fn roll_cycle(&mut self) {
|
||||
self.roll::<North>();
|
||||
self.roll::<West>();
|
||||
self.roll::<South>();
|
||||
self.roll::<East>();
|
||||
}
|
||||
|
||||
// find the first loop, return the iteration count when we first saw it and when we saw it again
|
||||
fn find_loop(&mut self) -> (usize, usize) {
|
||||
let mut first_seen = Vec::new();
|
||||
first_seen.push((self.matrix.clone(), 0));
|
||||
let mut i = 0;
|
||||
loop {
|
||||
self.roll_cycle();
|
||||
i += 1;
|
||||
if let Some((_, first_idx)) = first_seen.iter().find(|(val, _)| *val == self.matrix) {
|
||||
return (*first_idx, i);
|
||||
} else {
|
||||
first_seen.push((self.matrix.clone(), i));
|
||||
}
|
||||
}
|
||||
}
|
||||
fn score_rows<T: Direction>(&self) -> u64 {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Platform {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
self.matrix.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
// PROBLEM 1 solution
|
||||
|
||||
#[aoc(day14, part1)]
|
||||
fn part1(input: &str) -> u64 {
|
||||
let mut p = Platform::from(input);
|
||||
p.roll::<North>();
|
||||
p.score::<North>()
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
#[aoc(day14, part2)]
|
||||
fn part2(input: &str) -> u64 {
|
||||
const ITERATIONS: usize = 1000000000;
|
||||
let mut p = Platform::from(input);
|
||||
let first_loop = p.find_loop();
|
||||
let loop_length = first_loop.1 - first_loop.0;
|
||||
let cycles_to_skip = ((ITERATIONS - first_loop.0) / loop_length) * loop_length;
|
||||
let iterations_remaining = ITERATIONS - first_loop.0 - cycles_to_skip;
|
||||
|
||||
for _ in 0..iterations_remaining {
|
||||
p.roll_cycle();
|
||||
}
|
||||
|
||||
p.score::<North>()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "O....#....
|
||||
O.OO#....#
|
||||
.....##...
|
||||
OO.#O....O
|
||||
.O.....O#.
|
||||
O.#..O.#.#
|
||||
..O..#O..O
|
||||
.......O..
|
||||
#....###..
|
||||
#OO..#....";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(EXAMPLE), 136);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(EXAMPLE), 64);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
use aoc_runner_derive::aoc;
|
||||
use std::collections::HashMap;
|
||||
|
||||
// COMMON
|
||||
|
||||
fn hash_string(s: &str) -> u64 {
|
||||
s.bytes().fold(0u64, |mut accum, val| {
|
||||
accum += val as u64;
|
||||
accum *= 17;
|
||||
accum %= 256;
|
||||
accum
|
||||
})
|
||||
}
|
||||
|
||||
// PROBLEM 1 solution
|
||||
|
||||
#[aoc(day15, part1)]
|
||||
fn part1(input: &str) -> u64 {
|
||||
let line = input.lines().next().unwrap();
|
||||
line.split(',').map(|s| hash_string(s)).sum()
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct LensBox {
|
||||
// lenses k: lens label v: focal length
|
||||
lenses: HashMap<String, u8>,
|
||||
// order is the lens stack, values are labels into lenses
|
||||
order: Vec<String>,
|
||||
}
|
||||
|
||||
impl LensBox {
|
||||
fn add_lens(&mut self, label: &str, focal_length: u8) {
|
||||
// If there is not already a lens in the box with the same label, add
|
||||
// the lens to the box immediately behind any lenses already in the box.
|
||||
// Don't move any of the other lenses when you do this. If there aren't
|
||||
// any lenses in the box, the new lens goes all the way to the front of
|
||||
// the box.
|
||||
if self.lenses.insert(label.to_owned(), focal_length).is_none() {
|
||||
self.order.push(label.to_owned());
|
||||
}
|
||||
}
|
||||
//If the operation character is a dash (-), go to the relevant box and
|
||||
//remove the lens with the given label if it is present in the box. Then,
|
||||
//move any remaining lenses as far forward in the box as they can go without
|
||||
//changing their order, filling any space made by removing the indicated
|
||||
//lens. (If no lens in that box has the given label, nothing happens.)
|
||||
fn remove_lens_if_present(&mut self, label: &str) {
|
||||
if let Some(_) = self.lenses.remove(label) {
|
||||
self.order.remove(
|
||||
self.order
|
||||
.iter()
|
||||
.position(|s| s == label)
|
||||
.expect("We had the lens in lenses but not in order?!"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn total_lens_power(&self) -> u64 {
|
||||
self.order
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(lens_idx, label)| (lens_idx + 1) as u64 * self.lenses[label] as u64)
|
||||
.sum()
|
||||
}
|
||||
}
|
||||
|
||||
enum Instruction {
|
||||
Replace(String, u8),
|
||||
Remove(String),
|
||||
}
|
||||
|
||||
impl From<&str> for Instruction {
|
||||
fn from(s: &str) -> Self {
|
||||
let op_pos = s.find(|c| c == '-' || c == '=').expect("No operation?!");
|
||||
let op = s.chars().nth(op_pos).unwrap();
|
||||
let (label, op_focal) = s.split_once(|c| c == '-' || c == '=').unwrap();
|
||||
|
||||
match op {
|
||||
'-' => Self::Remove(label.to_owned()),
|
||||
'=' => Self::Replace(label.to_owned(), op_focal.parse().unwrap()),
|
||||
_ => panic!("unexpected op {}", op),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Instruction {
|
||||
fn execute(&self, boxes: &mut [LensBox; 256]) {
|
||||
match self {
|
||||
Self::Remove(label) => boxes[hash_string(label) as usize].remove_lens_if_present(label),
|
||||
Self::Replace(label, focal) => boxes[hash_string(label) as usize].add_lens(label, *focal),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
fn print_boxes(boxes: &[LensBox; 256]) {
|
||||
for (idx, b) in boxes.iter().enumerate() {
|
||||
if !b.order.is_empty() {
|
||||
// print!("Box {}:", idx);
|
||||
for label in &b.order {
|
||||
// print!(" [{} {}]", label, b.lenses[label]);
|
||||
}
|
||||
// println!();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[aoc(day15, part2)]
|
||||
fn part2(input: &str) -> u64 {
|
||||
let line = input.lines().next().unwrap();
|
||||
|
||||
let instructions: Vec<_> = line.split(',').map(|s| Instruction::from(s)).collect();
|
||||
let mut boxes: [LensBox; 256] = std::array::from_fn(|_| LensBox::default());
|
||||
|
||||
for inst in instructions {
|
||||
inst.execute(&mut boxes);
|
||||
}
|
||||
|
||||
boxes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(box_idx, b)| (box_idx + 1) as u64 * b.total_lens_power())
|
||||
.sum()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7";
|
||||
|
||||
#[test]
|
||||
fn problem1_test_hash() {
|
||||
assert_eq!(hash_string(&"HASH"), 52);
|
||||
}
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(EXAMPLE), 1320);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(EXAMPLE), 145);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use std::fmt::Display;
|
||||
use std::iter::repeat;
|
||||
|
||||
// PARSE
|
||||
|
||||
enum Interaction {
|
||||
One(FromDirection),
|
||||
Two((FromDirection, FromDirection)),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
|
||||
enum FromDirection {
|
||||
Left = 0,
|
||||
Above = 1,
|
||||
Right = 2,
|
||||
Below = 3,
|
||||
}
|
||||
|
||||
impl FromDirection {
|
||||
const fn mask(&self) -> u8 {
|
||||
1 << *self as u8
|
||||
}
|
||||
// return the new pos for a ray that will be from the direction.
|
||||
// a ray 'from' left 'goes' right
|
||||
const fn goes_pos(&self, pos: (i64, i64)) -> (i64, i64) {
|
||||
match self {
|
||||
Self::Left => (pos.0 + 1, pos.1),
|
||||
Self::Right => (pos.0 - 1, pos.1),
|
||||
Self::Above => (pos.0, pos.1 + 1),
|
||||
Self::Below => (pos.0, pos.1 - 1),
|
||||
}
|
||||
}
|
||||
const fn reflect_ne(&self) -> Self {
|
||||
match self {
|
||||
Self::Left => Self::Below,
|
||||
Self::Right => Self::Above,
|
||||
Self::Above => Self::Right,
|
||||
Self::Below => Self::Left,
|
||||
}
|
||||
}
|
||||
const fn opposite(&self) -> FromDirection {
|
||||
match self {
|
||||
Self::Left => Self::Right,
|
||||
Self::Right => Self::Left,
|
||||
Self::Above => Self::Below,
|
||||
Self::Below => Self::Above,
|
||||
}
|
||||
}
|
||||
const fn reflect_se(&self) -> FromDirection {
|
||||
self.reflect_ne().opposite()
|
||||
}
|
||||
fn interact(&self, tile: char) -> Interaction {
|
||||
match tile {
|
||||
'.' => Interaction::One(*self),
|
||||
'/' => Interaction::One(self.reflect_ne()),
|
||||
'\\' => Interaction::One(self.reflect_se()),
|
||||
'|' => match self {
|
||||
FromDirection::Above | FromDirection::Below => Interaction::One(*self),
|
||||
FromDirection::Left | FromDirection::Right => {
|
||||
Interaction::Two((FromDirection::Above, FromDirection::Below))
|
||||
}
|
||||
},
|
||||
'-' => match self {
|
||||
FromDirection::Left | FromDirection::Right => Interaction::One(*self),
|
||||
FromDirection::Above | FromDirection::Below => {
|
||||
Interaction::Two((FromDirection::Left, FromDirection::Right))
|
||||
}
|
||||
},
|
||||
c => panic!("invalid tile {}", c),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for FromDirection {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Above => f.write_str("above"),
|
||||
Self::Below => f.write_str("below"),
|
||||
Self::Left => f.write_str("left"),
|
||||
Self::Right => f.write_str("right"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Contraption {
|
||||
tiles: Vec<Vec<char>>,
|
||||
}
|
||||
|
||||
struct VisitState {
|
||||
visited_from: Vec<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl VisitState {
|
||||
fn visit(&mut self, pos: (i64, i64), dir: FromDirection) -> bool {
|
||||
let pos_state = &mut self.visited_from[pos.1 as usize][pos.0 as usize];
|
||||
if *pos_state & dir.mask() > 0 {
|
||||
false
|
||||
} else {
|
||||
*pos_state |= dir.mask();
|
||||
true
|
||||
}
|
||||
}
|
||||
fn score(&self) -> u64 {
|
||||
self.visited_from.iter().flatten().filter(|c| **c != 0).count() as u64
|
||||
}
|
||||
#[allow(dead_code)]
|
||||
#[allow(unused)]
|
||||
fn dump(&self) {
|
||||
// println!("Score {}:", self.score());
|
||||
for line in &self.visited_from {
|
||||
// println!(
|
||||
// " {}",
|
||||
// String::from_iter(line.iter().map(|b| if *b == 0 { '.' } else { '#' }))
|
||||
// );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Contraption {
|
||||
fn height(&self) -> i64 {
|
||||
self.tiles.len() as i64
|
||||
}
|
||||
fn width(&self) -> i64 {
|
||||
self.tiles[0].len() as i64
|
||||
}
|
||||
fn cast_ray(&self, pos: (i64, i64), dir: FromDirection) -> VisitState {
|
||||
self.cast_ray_inner(self.empty_state(), pos, dir)
|
||||
}
|
||||
fn cast_ray_inner(&self, mut state: VisitState, pos: (i64, i64), dir: FromDirection) -> VisitState {
|
||||
if pos.0 >= 0 && pos.1 >= 0 && pos.0 < self.width() && pos.1 < self.height() && state.visit(pos, dir) {
|
||||
match dir.interact(self.tiles[pos.1 as usize][pos.0 as usize]) {
|
||||
Interaction::One(dir) => self.cast_ray_inner(state, dir.goes_pos(pos), dir),
|
||||
Interaction::Two((dir1, dir2)) => self.cast_ray_inner(
|
||||
self.cast_ray_inner(state, dir2.goes_pos(pos), dir2),
|
||||
dir1.goes_pos(pos),
|
||||
dir1,
|
||||
),
|
||||
}
|
||||
} else {
|
||||
state
|
||||
}
|
||||
}
|
||||
fn empty_state(&self) -> VisitState {
|
||||
let mut visited_from = Vec::new();
|
||||
for _ in 0..self.height() {
|
||||
visited_from.push(Vec::from_iter(repeat(0).take(self.width() as usize)));
|
||||
}
|
||||
VisitState { visited_from }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for Contraption {
|
||||
fn from(input: &str) -> Self {
|
||||
let mut tiles = Vec::new();
|
||||
for line in input.lines() {
|
||||
tiles.push(line.chars().map(|c| c.into()).collect());
|
||||
}
|
||||
Contraption { tiles }
|
||||
}
|
||||
}
|
||||
|
||||
// PROBLEM 1 solution
|
||||
|
||||
#[aoc_generator(day16)]
|
||||
fn parse(input: &str) -> Contraption {
|
||||
Contraption::from(input)
|
||||
}
|
||||
|
||||
#[aoc(day16, part1)]
|
||||
fn part1(contraption: &Contraption) -> u64 {
|
||||
contraption.cast_ray((0, 0), FromDirection::Left).score()
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
#[aoc(day16, part2)]
|
||||
fn part2(contraption: &Contraption) -> u64 {
|
||||
let rows_max = (0..contraption.height()).fold(0, |max_tiles, y| {
|
||||
std::cmp::max(
|
||||
max_tiles,
|
||||
std::cmp::max(
|
||||
contraption.cast_ray((0, y), FromDirection::Left).score(),
|
||||
contraption
|
||||
.cast_ray((contraption.width() - 1, y), FromDirection::Right)
|
||||
.score(),
|
||||
),
|
||||
)
|
||||
});
|
||||
|
||||
let cols_max = (0..contraption.width()).fold(0, |max_tiles, x| {
|
||||
std::cmp::max(
|
||||
max_tiles,
|
||||
std::cmp::max(
|
||||
contraption.cast_ray((x, 0), FromDirection::Above).score(),
|
||||
contraption
|
||||
.cast_ray((x, contraption.height() - 1), FromDirection::Below)
|
||||
.score(),
|
||||
),
|
||||
)
|
||||
});
|
||||
|
||||
std::cmp::max(rows_max, cols_max)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = r".|...\....
|
||||
|.-.\.....
|
||||
.....|-...
|
||||
........|.
|
||||
..........
|
||||
.........\
|
||||
..../.\\..
|
||||
.-.-/..|..
|
||||
.|....-|.\
|
||||
..//.|....";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(&parse(EXAMPLE)), 46);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(&parse(EXAMPLE)), 51);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,458 @@
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use colormap::ColorMap;
|
||||
use std::collections::hash_map::RandomState;
|
||||
use std::collections::{BinaryHeap, HashMap};
|
||||
use std::io::Write;
|
||||
use std::iter::repeat;
|
||||
use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};
|
||||
|
||||
mod colormap;
|
||||
|
||||
const COLORMAP: &ColorMap = &colormap::COLORMAP_INFERNO;
|
||||
|
||||
// DATA
|
||||
|
||||
const UNPATH_CHAR: char = '█';
|
||||
const UNVISITED_CHAR: char = ' ';
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
|
||||
enum Direction {
|
||||
Left,
|
||||
Right,
|
||||
Up,
|
||||
Down,
|
||||
}
|
||||
|
||||
impl Direction {
|
||||
const fn all() -> &'static [Self; 4] {
|
||||
&[Direction::Left, Direction::Right, Direction::Up, Direction::Down]
|
||||
}
|
||||
const fn opposite(&self) -> Self {
|
||||
match self {
|
||||
Direction::Left => Direction::Right,
|
||||
Direction::Right => Direction::Left,
|
||||
Direction::Up => Direction::Down,
|
||||
Direction::Down => Direction::Up,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&Direction> for char {
|
||||
fn from(dir: &Direction) -> Self {
|
||||
match dir {
|
||||
Direction::Left => '←',
|
||||
Direction::Right => '→',
|
||||
Direction::Up => '↑',
|
||||
Direction::Down => '↓',
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct CityMap {
|
||||
map: Vec<Vec<u64>>,
|
||||
}
|
||||
|
||||
impl CityMap {
|
||||
fn offset_pos(&self, pos: (usize, usize), dir: &Direction) -> Option<(usize, usize)> {
|
||||
match dir {
|
||||
Direction::Left if pos.0 > 0 => Some((pos.0 - 1, pos.1)),
|
||||
Direction::Right if pos.0 < self.map[0].len() - 1 => Some((pos.0 + 1, pos.1)),
|
||||
Direction::Up if pos.1 > 0 => Some((pos.0, pos.1 - 1)),
|
||||
Direction::Down if pos.1 < self.map.len() - 1 => Some((pos.0, pos.1 + 1)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
#[allow(dead_code)]
|
||||
fn print(&self) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let cost_max = *self.map.iter().flat_map(|row| row.iter()).max().unwrap() as f64;
|
||||
|
||||
let mut so_lock = StandardStream::stdout(ColorChoice::Always);
|
||||
for y in 0..self.map.len() {
|
||||
for val in &self.map[y] {
|
||||
so_lock.set_color(
|
||||
ColorSpec::new()
|
||||
.set_bg(Some(COLORMAP.apply(*val as f64 / cost_max)))
|
||||
.set_fg(Some(Color::Black)),
|
||||
)?;
|
||||
so_lock.write_fmt(format_args!("{}", val))?;
|
||||
}
|
||||
so_lock.reset()?;
|
||||
writeln!(so_lock)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
type Position = (usize, usize);
|
||||
|
||||
struct WalkCost<'a> {
|
||||
start: Position,
|
||||
cost_from: Vec<Vec<HashMap<(Direction, usize), u64>>>,
|
||||
map: &'a CityMap,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Move {
|
||||
new_pos: Position,
|
||||
dir: &'static Direction,
|
||||
consecutive: usize,
|
||||
weight: u64,
|
||||
}
|
||||
|
||||
impl PartialEq for Move {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.weight == other.weight
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Move {}
|
||||
|
||||
impl PartialOrd for Move {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for Move {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
std::cmp::Reverse(self.weight).cmp(&std::cmp::Reverse(other.weight))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> WalkCost<'a> {
|
||||
fn from_map(map: &'a CityMap, start: Position) -> Self {
|
||||
Self {
|
||||
map,
|
||||
start,
|
||||
cost_from: map
|
||||
.map
|
||||
.iter()
|
||||
.map(|row| repeat(HashMap::new()).take(row.len()).collect())
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
fn compute(&mut self) {
|
||||
let mut unvisited_next_moves: BinaryHeap<Move> = BinaryHeap::new();
|
||||
let valid_start_moves: Vec<Move> = Direction::all()
|
||||
.iter()
|
||||
.filter_map(|dir| {
|
||||
self.map.offset_pos(self.start, dir).and_then(|pos| {
|
||||
Some(Move {
|
||||
new_pos: pos,
|
||||
dir,
|
||||
consecutive: 1,
|
||||
weight: self.map.map[pos.1][pos.0],
|
||||
})
|
||||
})
|
||||
}) // valid positions
|
||||
.collect();
|
||||
|
||||
for m in valid_start_moves {
|
||||
unvisited_next_moves.push(m);
|
||||
}
|
||||
|
||||
while let Some(cur_move) = unvisited_next_moves.pop() {
|
||||
// we've been here already at a lower cost
|
||||
// if cur_move.weight >= self.cost_to[cur_move.new_pos.1][cur_move.new_pos.0] {
|
||||
// continue;
|
||||
// }
|
||||
if let Some(last_weight) =
|
||||
self.cost_from[cur_move.new_pos.1][cur_move.new_pos.0].get(&(*cur_move.dir, cur_move.consecutive))
|
||||
{
|
||||
if cur_move.weight < *last_weight {
|
||||
self.cost_from[cur_move.new_pos.1][cur_move.new_pos.0]
|
||||
.insert((*cur_move.dir, cur_move.consecutive), cur_move.weight);
|
||||
} else {
|
||||
continue;
|
||||
} // visited before at lower cost }
|
||||
} else {
|
||||
self.cost_from[cur_move.new_pos.1][cur_move.new_pos.0]
|
||||
.insert((*cur_move.dir, cur_move.consecutive), cur_move.weight);
|
||||
}
|
||||
// println!("state at {:?}: {:?}", cur_move, self.cost_from[cur_move.new_pos.1][cur_move.new_pos.0]);
|
||||
|
||||
let valid_moves = Direction::all().iter().filter_map(|dir| {
|
||||
self.map
|
||||
.offset_pos(cur_move.new_pos, dir)
|
||||
.and_then(|new_pos| {
|
||||
Some(Move {
|
||||
new_pos,
|
||||
dir,
|
||||
consecutive: if cur_move.dir == dir {
|
||||
cur_move.consecutive + 1
|
||||
} else {
|
||||
1
|
||||
},
|
||||
weight: cur_move.weight + self.map.map[new_pos.1][new_pos.0],
|
||||
})
|
||||
})
|
||||
.filter(|m| m.consecutive != 4 && *m.dir != cur_move.dir.opposite())
|
||||
.filter(|m| {
|
||||
m.weight
|
||||
< *self.cost_from[m.new_pos.1][m.new_pos.0]
|
||||
.get(&(*m.dir, m.consecutive))
|
||||
.unwrap_or(&u64::MAX)
|
||||
})
|
||||
}); // valid positions
|
||||
// println!("valid moves with {:?}", cur_move);
|
||||
for next_move in valid_moves {
|
||||
// println!(" {:?}", next_move);
|
||||
unvisited_next_moves.push(next_move);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct WalkCost2<'a> {
|
||||
start: Position,
|
||||
cost_from: Vec<Vec<HashMap<(Direction, usize), u64>>>,
|
||||
map: &'a CityMap,
|
||||
}
|
||||
|
||||
impl<'a> WalkCost2<'a> {
|
||||
fn from_map(map: &'a CityMap, start: Position) -> Self {
|
||||
Self {
|
||||
map,
|
||||
start,
|
||||
cost_from: map
|
||||
.map
|
||||
.iter()
|
||||
.map(|row| repeat(HashMap::new()).take(row.len()).collect())
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
fn min_cost_at(&self, pos: Position) -> Option<&u64> {
|
||||
self.cost_from[pos.1][pos.0].values().min()
|
||||
}
|
||||
fn compute(&mut self, to: Position) {
|
||||
let mut unvisited_next_moves: BinaryHeap<Move> = BinaryHeap::new();
|
||||
let valid_start_moves: Vec<Move> = Direction::all()
|
||||
.iter()
|
||||
.filter_map(|dir| {
|
||||
self.map.offset_pos(self.start, dir).and_then(|pos| {
|
||||
Some(Move {
|
||||
new_pos: pos,
|
||||
dir,
|
||||
consecutive: 1,
|
||||
weight: self.map.map[pos.1][pos.0],
|
||||
})
|
||||
})
|
||||
}) // valid positions
|
||||
.collect();
|
||||
|
||||
for m in valid_start_moves {
|
||||
unvisited_next_moves.push(m);
|
||||
}
|
||||
|
||||
while let Some(cur_move) = unvisited_next_moves.pop() {
|
||||
// we've been here already at a lower cost
|
||||
// if cur_move.weight >= self.cost_to[cur_move.new_pos.1][cur_move.new_pos.0] {
|
||||
// continue;
|
||||
// }
|
||||
if let Some(last_weight) =
|
||||
self.cost_from[cur_move.new_pos.1][cur_move.new_pos.0].get(&(*cur_move.dir, cur_move.consecutive))
|
||||
{
|
||||
if cur_move.weight < *last_weight {
|
||||
self.cost_from[cur_move.new_pos.1][cur_move.new_pos.0]
|
||||
.insert((*cur_move.dir, cur_move.consecutive), cur_move.weight);
|
||||
// println!("move {:?} inserted {:?}", cur_move, (*cur_move.dir, cur_move.consecutive));
|
||||
} else {
|
||||
continue;
|
||||
} // visited before at lower cost }
|
||||
} else {
|
||||
// println!("move {:?} inserted {:?}", cur_move, (*cur_move.dir, cur_move.consecutive));
|
||||
self.cost_from[cur_move.new_pos.1][cur_move.new_pos.0]
|
||||
.insert((*cur_move.dir, cur_move.consecutive), cur_move.weight);
|
||||
}
|
||||
|
||||
if cur_move.new_pos == to {
|
||||
// println!("reached end pos {:?} via {:?}", to, cur_move);
|
||||
continue;
|
||||
}
|
||||
let valid_moves = Direction::all().iter().filter_map(|dir| {
|
||||
self.map
|
||||
.offset_pos(cur_move.new_pos, dir)
|
||||
.and_then(|new_pos| {
|
||||
Some(Move {
|
||||
new_pos,
|
||||
dir,
|
||||
consecutive: if cur_move.dir == dir {
|
||||
cur_move.consecutive + 1
|
||||
} else {
|
||||
1
|
||||
},
|
||||
weight: cur_move.weight + self.map.map[new_pos.1][new_pos.0],
|
||||
})
|
||||
})
|
||||
.filter(|m| m.new_pos != self.start)
|
||||
.filter(|m| *m.dir != cur_move.dir.opposite())
|
||||
.filter(|m| {
|
||||
if m.dir == cur_move.dir {
|
||||
m.consecutive < 11
|
||||
} else {
|
||||
cur_move.consecutive >= 4
|
||||
}
|
||||
})
|
||||
.filter(|m| m.new_pos != to || m.consecutive >= 4)
|
||||
.filter(|m| {
|
||||
m.weight
|
||||
< *self.cost_from[m.new_pos.1][m.new_pos.0]
|
||||
.get(&(*m.dir, m.consecutive))
|
||||
.unwrap_or(&u64::MAX)
|
||||
})
|
||||
}); // valid positions
|
||||
// println!("valid moves with {:?}", cur_move);
|
||||
for next_move in valid_moves {
|
||||
// println!(" {:?}", next_move);
|
||||
unvisited_next_moves.push(next_move);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn shortest_path_to(&self, to: Position) -> Vec<(Position, Direction)> {
|
||||
let mut path = Vec::new();
|
||||
let mut cur_pos = to;
|
||||
// start at the end, walk backwards
|
||||
while cur_pos != self.start {
|
||||
let (m, _val) = self.cost_from[cur_pos.1][cur_pos.0]
|
||||
.iter()
|
||||
.min_by(|a, b| a.1.cmp(b.1))
|
||||
.unwrap();
|
||||
path.push((cur_pos, m.0));
|
||||
cur_pos = self.map.offset_pos(cur_pos, &m.0.opposite()).unwrap();
|
||||
}
|
||||
path
|
||||
}
|
||||
#[allow(unused)]
|
||||
fn print_path(&self, to: Position) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let path = self.shortest_path_to(to);
|
||||
let map: HashMap<_, _, RandomState> = HashMap::from_iter(path.into_iter());
|
||||
let cost_max_of_min = *self
|
||||
.cost_from
|
||||
.iter()
|
||||
.flat_map(|row| row.iter().filter_map(|cell| cell.values().min()))
|
||||
.max()
|
||||
.unwrap() as f64;
|
||||
let mut so_lock = StandardStream::stdout(ColorChoice::Always);
|
||||
|
||||
for y in 0..self.cost_from.len() {
|
||||
for x in 0..self.map.map[y].len() {
|
||||
let mut color = ColorSpec::new();
|
||||
let c = if let Some(to_dir) = map.get(&(x, y)) {
|
||||
let normalized_cost = *self.min_cost_at((x, y)).unwrap() as f64 / cost_max_of_min;
|
||||
let bg_color = COLORMAP.apply(normalized_cost);
|
||||
let fg_color = if let Color::Rgb(r, g, b) = bg_color {
|
||||
Color::Rgb(255 - r, 255 - g, 255 - b)
|
||||
} else {
|
||||
Color::Black
|
||||
};
|
||||
color.set_fg(Some(fg_color)).set_bg(Some(bg_color)).bold();
|
||||
to_dir.into()
|
||||
} else {
|
||||
if let Some(cost) = &self.min_cost_at((x, y)) {
|
||||
color.set_fg(Some(COLORMAP.apply(**cost as f64 / cost_max_of_min)));
|
||||
UNPATH_CHAR
|
||||
} else {
|
||||
color.set_fg(Some(Color::Black));
|
||||
UNVISITED_CHAR
|
||||
}
|
||||
};
|
||||
so_lock.set_color(&color)?;
|
||||
let mut char_buf = [0u8; 4];
|
||||
c.encode_utf8(&mut char_buf);
|
||||
so_lock.write_all(&char_buf)?;
|
||||
}
|
||||
so_lock.reset()?;
|
||||
writeln!(so_lock)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for CityMap {
|
||||
fn from(input: &str) -> Self {
|
||||
Self {
|
||||
map: input
|
||||
.lines()
|
||||
.map(|l| l.chars().map(|c| c as u64 - '0' as u64).collect())
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// PROBLEM 1 solution
|
||||
|
||||
#[aoc_generator(day17)]
|
||||
fn parse(input: &str) -> CityMap {
|
||||
CityMap::from(input)
|
||||
}
|
||||
|
||||
#[aoc(day17, part1)]
|
||||
fn part1(map: &CityMap) -> u64 {
|
||||
let mut costs = WalkCost::from_map(map, (0, 0));
|
||||
costs.compute();
|
||||
|
||||
// println!("{}", costs);
|
||||
// costs.print_shortest_path((costs.cost_to[0].len() - 1, costs.cost_to.len() - 1));
|
||||
|
||||
*costs.cost_from[costs.cost_from.len() - 1][costs.cost_from[0].len() - 1]
|
||||
.values()
|
||||
.min()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
#[aoc(day17, part2)]
|
||||
fn part2(map: &CityMap) -> u64 {
|
||||
// map.print().unwrap();
|
||||
let mut costs = WalkCost2::from_map(map, (0, 0));
|
||||
costs.compute((map.map[0].len() - 1, map.map.len() - 1));
|
||||
|
||||
// println!("{}", costs);
|
||||
// costs
|
||||
// .print_path((costs.cost_from[0].len() - 1, costs.cost_from.len() - 1))
|
||||
// .unwrap();
|
||||
|
||||
*costs.cost_from[costs.cost_from.len() - 1][costs.cost_from[0].len() - 1]
|
||||
.values()
|
||||
.min()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rstest::rstest;
|
||||
|
||||
const EXAMPLE: &str = "2413432311323
|
||||
3215453535623
|
||||
3255245654254
|
||||
3446585845452
|
||||
4546657867536
|
||||
1438598798454
|
||||
4457876987766
|
||||
3637877979653
|
||||
4654967986887
|
||||
4564679986453
|
||||
1224686865563
|
||||
2546548887735
|
||||
4322674655533";
|
||||
|
||||
const EXAMPLE2: &str = "111111111111
|
||||
999999999991
|
||||
999999999991
|
||||
999999999991
|
||||
999999999991";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(&parse(EXAMPLE)), 102);
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case(EXAMPLE, 94)]
|
||||
#[case(EXAMPLE2, 71)]
|
||||
fn part2_example(#[case] example: &str, #[case] expect: u64) {
|
||||
assert_eq!(part2(&parse(example)), expect);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,531 @@
|
||||
use termcolor::Color;
|
||||
|
||||
pub struct ColorMap(&'static [Color]);
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub const COLORMAP_SMOOTH_COOLWARM: ColorMap = ColorMap(&[
|
||||
Color::Rgb(59, 76, 19),
|
||||
Color::Rgb(60, 78, 19),
|
||||
Color::Rgb(61, 80, 19),
|
||||
Color::Rgb(62, 81, 19),
|
||||
Color::Rgb(63, 83, 19),
|
||||
Color::Rgb(64, 85, 20),
|
||||
Color::Rgb(66, 87, 20),
|
||||
Color::Rgb(67, 88, 20),
|
||||
Color::Rgb(68, 90, 20),
|
||||
Color::Rgb(69, 92, 20),
|
||||
Color::Rgb(70, 94, 20),
|
||||
Color::Rgb(72, 95, 20),
|
||||
Color::Rgb(73, 97, 21),
|
||||
Color::Rgb(74, 99, 21),
|
||||
Color::Rgb(75, 100, 21),
|
||||
Color::Rgb(76, 102, 21),
|
||||
Color::Rgb(78, 104, 21),
|
||||
Color::Rgb(79, 106, 21),
|
||||
Color::Rgb(80, 107, 21),
|
||||
Color::Rgb(81, 109, 21),
|
||||
Color::Rgb(83, 111, 22),
|
||||
Color::Rgb(84, 112, 22),
|
||||
Color::Rgb(85, 114, 22),
|
||||
Color::Rgb(86, 116, 22),
|
||||
Color::Rgb(88, 117, 22),
|
||||
Color::Rgb(89, 119, 22),
|
||||
Color::Rgb(90, 120, 22),
|
||||
Color::Rgb(91, 122, 22),
|
||||
Color::Rgb(93, 124, 23),
|
||||
Color::Rgb(94, 125, 23),
|
||||
Color::Rgb(95, 127, 23),
|
||||
Color::Rgb(97, 129, 23),
|
||||
Color::Rgb(98, 130, 23),
|
||||
Color::Rgb(99, 132, 23),
|
||||
Color::Rgb(101, 133, 23),
|
||||
Color::Rgb(102, 135, 23),
|
||||
Color::Rgb(103, 136, 23),
|
||||
Color::Rgb(105, 138, 23),
|
||||
Color::Rgb(106, 140, 24),
|
||||
Color::Rgb(107, 141, 24),
|
||||
Color::Rgb(109, 143, 24),
|
||||
Color::Rgb(110, 144, 24),
|
||||
Color::Rgb(111, 146, 24),
|
||||
Color::Rgb(113, 147, 24),
|
||||
Color::Rgb(114, 149, 24),
|
||||
Color::Rgb(115, 150, 24),
|
||||
Color::Rgb(117, 152, 24),
|
||||
Color::Rgb(118, 153, 24),
|
||||
Color::Rgb(119, 154, 24),
|
||||
Color::Rgb(121, 156, 24),
|
||||
Color::Rgb(122, 157, 24),
|
||||
Color::Rgb(123, 159, 24),
|
||||
Color::Rgb(125, 160, 24),
|
||||
Color::Rgb(126, 162, 25),
|
||||
Color::Rgb(128, 163, 25),
|
||||
Color::Rgb(129, 164, 25),
|
||||
Color::Rgb(130, 166, 25),
|
||||
Color::Rgb(132, 167, 25),
|
||||
Color::Rgb(133, 168, 25),
|
||||
Color::Rgb(134, 170, 25),
|
||||
Color::Rgb(136, 171, 25),
|
||||
Color::Rgb(137, 172, 25),
|
||||
Color::Rgb(139, 174, 25),
|
||||
Color::Rgb(140, 175, 25),
|
||||
Color::Rgb(141, 176, 25),
|
||||
Color::Rgb(143, 177, 25),
|
||||
Color::Rgb(144, 178, 25),
|
||||
Color::Rgb(146, 180, 25),
|
||||
Color::Rgb(147, 181, 25),
|
||||
Color::Rgb(148, 182, 25),
|
||||
Color::Rgb(150, 183, 25),
|
||||
Color::Rgb(151, 184, 25),
|
||||
Color::Rgb(153, 186, 25),
|
||||
Color::Rgb(154, 187, 25),
|
||||
Color::Rgb(155, 188, 25),
|
||||
Color::Rgb(157, 189, 25),
|
||||
Color::Rgb(158, 190, 25),
|
||||
Color::Rgb(159, 191, 25),
|
||||
Color::Rgb(161, 192, 25),
|
||||
Color::Rgb(162, 193, 25),
|
||||
Color::Rgb(163, 194, 25),
|
||||
Color::Rgb(165, 195, 25),
|
||||
Color::Rgb(166, 196, 25),
|
||||
Color::Rgb(168, 197, 25),
|
||||
Color::Rgb(169, 198, 25),
|
||||
Color::Rgb(170, 199, 25),
|
||||
Color::Rgb(172, 200, 25),
|
||||
Color::Rgb(173, 201, 25),
|
||||
Color::Rgb(174, 201, 25),
|
||||
Color::Rgb(176, 202, 25),
|
||||
Color::Rgb(177, 203, 25),
|
||||
Color::Rgb(178, 204, 25),
|
||||
Color::Rgb(180, 205, 25),
|
||||
Color::Rgb(181, 206, 25),
|
||||
Color::Rgb(182, 206, 25),
|
||||
Color::Rgb(183, 207, 24),
|
||||
Color::Rgb(185, 208, 24),
|
||||
Color::Rgb(186, 209, 24),
|
||||
Color::Rgb(187, 209, 24),
|
||||
Color::Rgb(189, 210, 24),
|
||||
Color::Rgb(190, 211, 24),
|
||||
Color::Rgb(191, 211, 24),
|
||||
Color::Rgb(192, 212, 24),
|
||||
Color::Rgb(193, 212, 24),
|
||||
Color::Rgb(195, 213, 24),
|
||||
Color::Rgb(196, 214, 24),
|
||||
Color::Rgb(197, 214, 24),
|
||||
Color::Rgb(198, 215, 24),
|
||||
Color::Rgb(200, 215, 24),
|
||||
Color::Rgb(201, 216, 24),
|
||||
Color::Rgb(202, 216, 23),
|
||||
Color::Rgb(203, 216, 23),
|
||||
Color::Rgb(204, 217, 23),
|
||||
Color::Rgb(205, 217, 23),
|
||||
Color::Rgb(206, 218, 23),
|
||||
Color::Rgb(208, 218, 23),
|
||||
Color::Rgb(209, 218, 23),
|
||||
Color::Rgb(210, 219, 23),
|
||||
Color::Rgb(211, 219, 23),
|
||||
Color::Rgb(212, 219, 23),
|
||||
Color::Rgb(213, 219, 22),
|
||||
Color::Rgb(214, 220, 22),
|
||||
Color::Rgb(215, 220, 22),
|
||||
Color::Rgb(216, 220, 22),
|
||||
Color::Rgb(217, 220, 22),
|
||||
Color::Rgb(218, 220, 22),
|
||||
Color::Rgb(219, 221, 22),
|
||||
Color::Rgb(220, 221, 22),
|
||||
Color::Rgb(221, 220, 22),
|
||||
Color::Rgb(222, 220, 21),
|
||||
Color::Rgb(223, 220, 21),
|
||||
Color::Rgb(225, 219, 21),
|
||||
Color::Rgb(226, 218, 21),
|
||||
Color::Rgb(227, 218, 21),
|
||||
Color::Rgb(228, 217, 21),
|
||||
Color::Rgb(229, 217, 21),
|
||||
Color::Rgb(229, 216, 20),
|
||||
Color::Rgb(230, 216, 20),
|
||||
Color::Rgb(231, 215, 20),
|
||||
Color::Rgb(232, 214, 20),
|
||||
Color::Rgb(233, 214, 20),
|
||||
Color::Rgb(234, 213, 20),
|
||||
Color::Rgb(235, 212, 20),
|
||||
Color::Rgb(235, 211, 19),
|
||||
Color::Rgb(236, 211, 19),
|
||||
Color::Rgb(237, 210, 19),
|
||||
Color::Rgb(238, 209, 19),
|
||||
Color::Rgb(238, 208, 19),
|
||||
Color::Rgb(239, 207, 19),
|
||||
Color::Rgb(239, 206, 18),
|
||||
Color::Rgb(240, 206, 18),
|
||||
Color::Rgb(241, 205, 18),
|
||||
Color::Rgb(241, 204, 18),
|
||||
Color::Rgb(242, 203, 18),
|
||||
Color::Rgb(242, 202, 18),
|
||||
Color::Rgb(243, 201, 18),
|
||||
Color::Rgb(243, 200, 17),
|
||||
Color::Rgb(244, 199, 17),
|
||||
Color::Rgb(244, 198, 17),
|
||||
Color::Rgb(244, 197, 17),
|
||||
Color::Rgb(245, 196, 17),
|
||||
Color::Rgb(245, 195, 17),
|
||||
Color::Rgb(245, 193, 16),
|
||||
Color::Rgb(246, 192, 16),
|
||||
Color::Rgb(246, 191, 16),
|
||||
Color::Rgb(246, 190, 16),
|
||||
Color::Rgb(246, 189, 16),
|
||||
Color::Rgb(247, 188, 16),
|
||||
Color::Rgb(247, 186, 15),
|
||||
Color::Rgb(247, 185, 15),
|
||||
Color::Rgb(247, 184, 15),
|
||||
Color::Rgb(247, 183, 15),
|
||||
Color::Rgb(247, 181, 15),
|
||||
Color::Rgb(247, 180, 15),
|
||||
Color::Rgb(247, 179, 15),
|
||||
Color::Rgb(247, 177, 14),
|
||||
Color::Rgb(247, 176, 14),
|
||||
Color::Rgb(247, 175, 14),
|
||||
Color::Rgb(247, 173, 14),
|
||||
Color::Rgb(247, 172, 14),
|
||||
Color::Rgb(247, 171, 14),
|
||||
Color::Rgb(247, 169, 13),
|
||||
Color::Rgb(247, 168, 13),
|
||||
Color::Rgb(247, 166, 13),
|
||||
Color::Rgb(246, 165, 13),
|
||||
Color::Rgb(246, 163, 13),
|
||||
Color::Rgb(246, 162, 13),
|
||||
Color::Rgb(246, 160, 12),
|
||||
Color::Rgb(245, 159, 12),
|
||||
Color::Rgb(245, 157, 12),
|
||||
Color::Rgb(245, 156, 12),
|
||||
Color::Rgb(244, 154, 12),
|
||||
Color::Rgb(244, 153, 12),
|
||||
Color::Rgb(244, 151, 12),
|
||||
Color::Rgb(243, 149, 11),
|
||||
Color::Rgb(243, 148, 11),
|
||||
Color::Rgb(242, 146, 11),
|
||||
Color::Rgb(242, 144, 11),
|
||||
Color::Rgb(241, 143, 11),
|
||||
Color::Rgb(241, 141, 11),
|
||||
Color::Rgb(240, 139, 11),
|
||||
Color::Rgb(240, 138, 10),
|
||||
Color::Rgb(239, 136, 10),
|
||||
Color::Rgb(238, 134, 10),
|
||||
Color::Rgb(238, 133, 10),
|
||||
Color::Rgb(237, 131, 10),
|
||||
Color::Rgb(237, 129, 10),
|
||||
Color::Rgb(236, 127, 99),
|
||||
Color::Rgb(235, 125, 98),
|
||||
Color::Rgb(234, 124, 96),
|
||||
Color::Rgb(234, 122, 95),
|
||||
Color::Rgb(233, 120, 93),
|
||||
Color::Rgb(232, 118, 92),
|
||||
Color::Rgb(231, 116, 91),
|
||||
Color::Rgb(230, 114, 89),
|
||||
Color::Rgb(229, 112, 88),
|
||||
Color::Rgb(229, 111, 86),
|
||||
Color::Rgb(228, 109, 85),
|
||||
Color::Rgb(227, 107, 84),
|
||||
Color::Rgb(226, 105, 82),
|
||||
Color::Rgb(225, 103, 81),
|
||||
Color::Rgb(224, 101, 79),
|
||||
Color::Rgb(223, 99, 78),
|
||||
Color::Rgb(222, 97, 77),
|
||||
Color::Rgb(221, 95, 75),
|
||||
Color::Rgb(220, 93, 74),
|
||||
Color::Rgb(219, 91, 73),
|
||||
Color::Rgb(218, 89, 71),
|
||||
Color::Rgb(216, 86, 70),
|
||||
Color::Rgb(215, 84, 69),
|
||||
Color::Rgb(214, 82, 68),
|
||||
Color::Rgb(213, 80, 66),
|
||||
Color::Rgb(212, 78, 65),
|
||||
Color::Rgb(211, 76, 64),
|
||||
Color::Rgb(209, 73, 62),
|
||||
Color::Rgb(208, 71, 61),
|
||||
Color::Rgb(207, 69, 60),
|
||||
Color::Rgb(206, 67, 59),
|
||||
Color::Rgb(204, 64, 57),
|
||||
Color::Rgb(203, 62, 56),
|
||||
Color::Rgb(202, 59, 55),
|
||||
Color::Rgb(200, 57, 54),
|
||||
Color::Rgb(199, 54, 53),
|
||||
Color::Rgb(198, 52, 52),
|
||||
Color::Rgb(196, 49, 50),
|
||||
Color::Rgb(195, 46, 49),
|
||||
Color::Rgb(193, 43, 48),
|
||||
Color::Rgb(192, 40, 47),
|
||||
Color::Rgb(191, 37, 46),
|
||||
Color::Rgb(189, 34, 45),
|
||||
Color::Rgb(188, 30, 44),
|
||||
Color::Rgb(186, 26, 43),
|
||||
Color::Rgb(185, 22, 41),
|
||||
Color::Rgb(183, 17, 40),
|
||||
Color::Rgb(182, 11, 39),
|
||||
Color::Rgb(180, 4, 38),
|
||||
]);
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub const COLORMAP_INFERNO: ColorMap = ColorMap(&[
|
||||
Color::Rgb(0, 0, 4),
|
||||
Color::Rgb(1, 0, 5),
|
||||
Color::Rgb(1, 1, 6),
|
||||
Color::Rgb(1, 1, 8),
|
||||
Color::Rgb(2, 1, 10),
|
||||
Color::Rgb(2, 2, 12),
|
||||
Color::Rgb(2, 2, 14),
|
||||
Color::Rgb(3, 2, 16),
|
||||
Color::Rgb(4, 3, 18),
|
||||
Color::Rgb(4, 3, 20),
|
||||
Color::Rgb(5, 4, 23),
|
||||
Color::Rgb(6, 4, 25),
|
||||
Color::Rgb(7, 5, 27),
|
||||
Color::Rgb(8, 5, 29),
|
||||
Color::Rgb(9, 6, 31),
|
||||
Color::Rgb(10, 7, 34),
|
||||
Color::Rgb(11, 7, 36),
|
||||
Color::Rgb(12, 8, 38),
|
||||
Color::Rgb(13, 8, 41),
|
||||
Color::Rgb(14, 9, 43),
|
||||
Color::Rgb(16, 9, 45),
|
||||
Color::Rgb(17, 10, 48),
|
||||
Color::Rgb(18, 10, 50),
|
||||
Color::Rgb(20, 11, 52),
|
||||
Color::Rgb(21, 11, 55),
|
||||
Color::Rgb(22, 11, 57),
|
||||
Color::Rgb(24, 12, 60),
|
||||
Color::Rgb(25, 12, 62),
|
||||
Color::Rgb(27, 12, 65),
|
||||
Color::Rgb(28, 12, 67),
|
||||
Color::Rgb(30, 12, 69),
|
||||
Color::Rgb(31, 12, 72),
|
||||
Color::Rgb(33, 12, 74),
|
||||
Color::Rgb(35, 12, 76),
|
||||
Color::Rgb(36, 12, 79),
|
||||
Color::Rgb(38, 12, 81),
|
||||
Color::Rgb(40, 11, 83),
|
||||
Color::Rgb(41, 11, 85),
|
||||
Color::Rgb(43, 11, 87),
|
||||
Color::Rgb(45, 11, 89),
|
||||
Color::Rgb(47, 10, 91),
|
||||
Color::Rgb(49, 10, 92),
|
||||
Color::Rgb(50, 10, 94),
|
||||
Color::Rgb(52, 10, 95),
|
||||
Color::Rgb(54, 9, 97),
|
||||
Color::Rgb(56, 9, 98),
|
||||
Color::Rgb(57, 9, 99),
|
||||
Color::Rgb(59, 9, 100),
|
||||
Color::Rgb(61, 9, 101),
|
||||
Color::Rgb(62, 9, 102),
|
||||
Color::Rgb(64, 10, 103),
|
||||
Color::Rgb(66, 10, 104),
|
||||
Color::Rgb(68, 10, 104),
|
||||
Color::Rgb(69, 10, 105),
|
||||
Color::Rgb(71, 11, 106),
|
||||
Color::Rgb(73, 11, 106),
|
||||
Color::Rgb(74, 12, 107),
|
||||
Color::Rgb(76, 12, 107),
|
||||
Color::Rgb(77, 13, 108),
|
||||
Color::Rgb(79, 13, 108),
|
||||
Color::Rgb(81, 14, 108),
|
||||
Color::Rgb(82, 14, 109),
|
||||
Color::Rgb(84, 15, 109),
|
||||
Color::Rgb(85, 15, 109),
|
||||
Color::Rgb(87, 16, 110),
|
||||
Color::Rgb(89, 16, 110),
|
||||
Color::Rgb(90, 17, 110),
|
||||
Color::Rgb(92, 18, 110),
|
||||
Color::Rgb(93, 18, 110),
|
||||
Color::Rgb(95, 19, 110),
|
||||
Color::Rgb(97, 19, 110),
|
||||
Color::Rgb(98, 20, 110),
|
||||
Color::Rgb(100, 21, 110),
|
||||
Color::Rgb(101, 21, 110),
|
||||
Color::Rgb(103, 22, 110),
|
||||
Color::Rgb(105, 22, 110),
|
||||
Color::Rgb(106, 23, 110),
|
||||
Color::Rgb(108, 24, 110),
|
||||
Color::Rgb(109, 24, 110),
|
||||
Color::Rgb(111, 25, 110),
|
||||
Color::Rgb(113, 25, 110),
|
||||
Color::Rgb(114, 26, 110),
|
||||
Color::Rgb(116, 26, 110),
|
||||
Color::Rgb(117, 27, 110),
|
||||
Color::Rgb(119, 28, 109),
|
||||
Color::Rgb(120, 28, 109),
|
||||
Color::Rgb(122, 29, 109),
|
||||
Color::Rgb(124, 29, 109),
|
||||
Color::Rgb(125, 30, 109),
|
||||
Color::Rgb(127, 30, 108),
|
||||
Color::Rgb(128, 31, 108),
|
||||
Color::Rgb(130, 32, 108),
|
||||
Color::Rgb(132, 32, 107),
|
||||
Color::Rgb(133, 33, 107),
|
||||
Color::Rgb(135, 33, 107),
|
||||
Color::Rgb(136, 34, 106),
|
||||
Color::Rgb(138, 34, 106),
|
||||
Color::Rgb(140, 35, 105),
|
||||
Color::Rgb(141, 35, 105),
|
||||
Color::Rgb(143, 36, 105),
|
||||
Color::Rgb(144, 37, 104),
|
||||
Color::Rgb(146, 37, 104),
|
||||
Color::Rgb(147, 38, 103),
|
||||
Color::Rgb(149, 38, 103),
|
||||
Color::Rgb(151, 39, 102),
|
||||
Color::Rgb(152, 39, 102),
|
||||
Color::Rgb(154, 40, 101),
|
||||
Color::Rgb(155, 41, 100),
|
||||
Color::Rgb(157, 41, 100),
|
||||
Color::Rgb(159, 42, 99),
|
||||
Color::Rgb(160, 42, 99),
|
||||
Color::Rgb(162, 43, 98),
|
||||
Color::Rgb(163, 44, 97),
|
||||
Color::Rgb(165, 44, 96),
|
||||
Color::Rgb(166, 45, 96),
|
||||
Color::Rgb(168, 46, 95),
|
||||
Color::Rgb(169, 46, 94),
|
||||
Color::Rgb(171, 47, 94),
|
||||
Color::Rgb(173, 48, 93),
|
||||
Color::Rgb(174, 48, 92),
|
||||
Color::Rgb(176, 49, 91),
|
||||
Color::Rgb(177, 50, 90),
|
||||
Color::Rgb(179, 50, 90),
|
||||
Color::Rgb(180, 51, 89),
|
||||
Color::Rgb(182, 52, 88),
|
||||
Color::Rgb(183, 53, 87),
|
||||
Color::Rgb(185, 53, 86),
|
||||
Color::Rgb(186, 54, 85),
|
||||
Color::Rgb(188, 55, 84),
|
||||
Color::Rgb(189, 56, 83),
|
||||
Color::Rgb(191, 57, 82),
|
||||
Color::Rgb(192, 58, 81),
|
||||
Color::Rgb(193, 58, 80),
|
||||
Color::Rgb(195, 59, 79),
|
||||
Color::Rgb(196, 60, 78),
|
||||
Color::Rgb(198, 61, 77),
|
||||
Color::Rgb(199, 62, 76),
|
||||
Color::Rgb(200, 63, 75),
|
||||
Color::Rgb(202, 64, 74),
|
||||
Color::Rgb(203, 65, 73),
|
||||
Color::Rgb(204, 66, 72),
|
||||
Color::Rgb(206, 67, 71),
|
||||
Color::Rgb(207, 68, 70),
|
||||
Color::Rgb(208, 69, 69),
|
||||
Color::Rgb(210, 70, 68),
|
||||
Color::Rgb(211, 71, 67),
|
||||
Color::Rgb(212, 72, 66),
|
||||
Color::Rgb(213, 74, 65),
|
||||
Color::Rgb(215, 75, 63),
|
||||
Color::Rgb(216, 76, 62),
|
||||
Color::Rgb(217, 77, 61),
|
||||
Color::Rgb(218, 78, 60),
|
||||
Color::Rgb(219, 80, 59),
|
||||
Color::Rgb(221, 81, 58),
|
||||
Color::Rgb(222, 82, 56),
|
||||
Color::Rgb(223, 83, 55),
|
||||
Color::Rgb(224, 85, 54),
|
||||
Color::Rgb(225, 86, 53),
|
||||
Color::Rgb(226, 87, 52),
|
||||
Color::Rgb(227, 89, 51),
|
||||
Color::Rgb(228, 90, 49),
|
||||
Color::Rgb(229, 92, 48),
|
||||
Color::Rgb(230, 93, 47),
|
||||
Color::Rgb(231, 94, 46),
|
||||
Color::Rgb(232, 96, 45),
|
||||
Color::Rgb(233, 97, 43),
|
||||
Color::Rgb(234, 99, 42),
|
||||
Color::Rgb(235, 100, 41),
|
||||
Color::Rgb(235, 102, 40),
|
||||
Color::Rgb(236, 103, 38),
|
||||
Color::Rgb(237, 105, 37),
|
||||
Color::Rgb(238, 106, 36),
|
||||
Color::Rgb(239, 108, 35),
|
||||
Color::Rgb(239, 110, 33),
|
||||
Color::Rgb(240, 111, 32),
|
||||
Color::Rgb(241, 113, 31),
|
||||
Color::Rgb(241, 115, 29),
|
||||
Color::Rgb(242, 116, 28),
|
||||
Color::Rgb(243, 118, 27),
|
||||
Color::Rgb(243, 120, 25),
|
||||
Color::Rgb(244, 121, 24),
|
||||
Color::Rgb(245, 123, 23),
|
||||
Color::Rgb(245, 125, 21),
|
||||
Color::Rgb(246, 126, 20),
|
||||
Color::Rgb(246, 128, 19),
|
||||
Color::Rgb(247, 130, 18),
|
||||
Color::Rgb(247, 132, 16),
|
||||
Color::Rgb(248, 133, 15),
|
||||
Color::Rgb(248, 135, 14),
|
||||
Color::Rgb(248, 137, 12),
|
||||
Color::Rgb(249, 139, 11),
|
||||
Color::Rgb(249, 140, 10),
|
||||
Color::Rgb(249, 142, 9),
|
||||
Color::Rgb(250, 144, 8),
|
||||
Color::Rgb(250, 146, 7),
|
||||
Color::Rgb(250, 148, 7),
|
||||
Color::Rgb(251, 150, 6),
|
||||
Color::Rgb(251, 151, 6),
|
||||
Color::Rgb(251, 153, 6),
|
||||
Color::Rgb(251, 155, 6),
|
||||
Color::Rgb(251, 157, 7),
|
||||
Color::Rgb(252, 159, 7),
|
||||
Color::Rgb(252, 161, 8),
|
||||
Color::Rgb(252, 163, 9),
|
||||
Color::Rgb(252, 165, 10),
|
||||
Color::Rgb(252, 166, 12),
|
||||
Color::Rgb(252, 168, 13),
|
||||
Color::Rgb(252, 170, 15),
|
||||
Color::Rgb(252, 172, 17),
|
||||
Color::Rgb(252, 174, 18),
|
||||
Color::Rgb(252, 176, 20),
|
||||
Color::Rgb(252, 178, 22),
|
||||
Color::Rgb(252, 180, 24),
|
||||
Color::Rgb(251, 182, 26),
|
||||
Color::Rgb(251, 184, 29),
|
||||
Color::Rgb(251, 186, 31),
|
||||
Color::Rgb(251, 188, 33),
|
||||
Color::Rgb(251, 190, 35),
|
||||
Color::Rgb(250, 192, 38),
|
||||
Color::Rgb(250, 194, 40),
|
||||
Color::Rgb(250, 196, 42),
|
||||
Color::Rgb(250, 198, 45),
|
||||
Color::Rgb(249, 199, 47),
|
||||
Color::Rgb(249, 201, 50),
|
||||
Color::Rgb(249, 203, 53),
|
||||
Color::Rgb(248, 205, 55),
|
||||
Color::Rgb(248, 207, 58),
|
||||
Color::Rgb(247, 209, 61),
|
||||
Color::Rgb(247, 211, 64),
|
||||
Color::Rgb(246, 213, 67),
|
||||
Color::Rgb(246, 215, 70),
|
||||
Color::Rgb(245, 217, 73),
|
||||
Color::Rgb(245, 219, 76),
|
||||
Color::Rgb(244, 221, 79),
|
||||
Color::Rgb(244, 223, 83),
|
||||
Color::Rgb(244, 225, 86),
|
||||
Color::Rgb(243, 227, 90),
|
||||
Color::Rgb(243, 229, 93),
|
||||
Color::Rgb(242, 230, 97),
|
||||
Color::Rgb(242, 232, 101),
|
||||
Color::Rgb(242, 234, 105),
|
||||
Color::Rgb(241, 236, 109),
|
||||
Color::Rgb(241, 237, 113),
|
||||
Color::Rgb(241, 239, 117),
|
||||
Color::Rgb(241, 241, 121),
|
||||
Color::Rgb(242, 242, 125),
|
||||
Color::Rgb(242, 244, 130),
|
||||
Color::Rgb(243, 245, 134),
|
||||
Color::Rgb(243, 246, 138),
|
||||
Color::Rgb(244, 248, 142),
|
||||
Color::Rgb(245, 249, 146),
|
||||
Color::Rgb(246, 250, 150),
|
||||
Color::Rgb(248, 251, 154),
|
||||
Color::Rgb(249, 252, 157),
|
||||
Color::Rgb(250, 253, 161),
|
||||
Color::Rgb(252, 255, 164),
|
||||
]);
|
||||
|
||||
impl ColorMap {
|
||||
pub fn apply(&self, val: f64) -> Color {
|
||||
assert!(val >= 0.0 && val <= 1.0);
|
||||
let position = (val * 255.0).ceil() as usize;
|
||||
self.0[position]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
use aoc_runner_derive::aoc;
|
||||
use itertools::Itertools;
|
||||
use std::collections::LinkedList;
|
||||
use std::str::Lines;
|
||||
|
||||
// DATA
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
|
||||
enum Direction {
|
||||
Left,
|
||||
Right,
|
||||
Up,
|
||||
Down,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
|
||||
enum Turn {
|
||||
LeftNinety,
|
||||
RightNinety,
|
||||
OneEighty,
|
||||
None,
|
||||
}
|
||||
|
||||
impl Direction {
|
||||
const fn all() -> &'static [Self; 4] {
|
||||
&[Direction::Left, Direction::Right, Direction::Up, Direction::Down]
|
||||
}
|
||||
const fn opposite(&self) -> Self {
|
||||
match self {
|
||||
Direction::Left => Direction::Right,
|
||||
Direction::Right => Direction::Left,
|
||||
Direction::Up => Direction::Down,
|
||||
Direction::Down => Direction::Up,
|
||||
}
|
||||
}
|
||||
const fn offset(&self) -> (isize, isize) {
|
||||
match self {
|
||||
Direction::Left => (-1, 0),
|
||||
Direction::Right => (1, 0),
|
||||
Direction::Up => (0, -1),
|
||||
Direction::Down => (0, 1),
|
||||
}
|
||||
}
|
||||
fn turn_kind(&self, next_dir: Direction) -> Turn {
|
||||
if *self == next_dir {
|
||||
Turn::None
|
||||
} else if self.opposite() == next_dir {
|
||||
Turn::OneEighty
|
||||
} else {
|
||||
match self {
|
||||
Direction::Left if next_dir == Direction::Up => Turn::RightNinety,
|
||||
Direction::Left if next_dir == Direction::Down => Turn::LeftNinety,
|
||||
Direction::Right if next_dir == Direction::Up => Turn::LeftNinety,
|
||||
Direction::Right if next_dir == Direction::Down => Turn::RightNinety,
|
||||
Direction::Up if next_dir == Direction::Left => Turn::LeftNinety,
|
||||
Direction::Up if next_dir == Direction::Right => Turn::RightNinety,
|
||||
Direction::Down if next_dir == Direction::Right => Turn::LeftNinety,
|
||||
Direction::Down if next_dir == Direction::Left => Turn::RightNinety,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for Direction {
|
||||
fn from(s: &str) -> Self {
|
||||
match s {
|
||||
"L" => Direction::Left,
|
||||
"R" => Direction::Right,
|
||||
"U" => Direction::Up,
|
||||
"D" => Direction::Down,
|
||||
s => panic!("{} is not a valid direction", s),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&Direction> for char {
|
||||
fn from(dir: &Direction) -> Self {
|
||||
match dir {
|
||||
Direction::Left => '←',
|
||||
Direction::Right => '→',
|
||||
Direction::Up => '↑',
|
||||
Direction::Down => '↓',
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct DigInstruction {
|
||||
dir: Direction,
|
||||
count: usize,
|
||||
color: String,
|
||||
}
|
||||
|
||||
impl From<&str> for DigInstruction {
|
||||
fn from(s: &str) -> Self {
|
||||
let mut parts = s.split_ascii_whitespace();
|
||||
let (dir, count, color) = (
|
||||
parts.next().unwrap(),
|
||||
parts.next().unwrap(),
|
||||
parts.next().unwrap().chars().skip(2).take(6).collect::<String>(),
|
||||
);
|
||||
Self {
|
||||
dir: dir.into(),
|
||||
count: count.parse().unwrap(),
|
||||
color: color.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DigInstruction {
|
||||
fn part2_transform(&mut self) {
|
||||
let (distance_s, direction_s) = self.color.split_at(5);
|
||||
self.count = usize::from_str_radix(distance_s, 16).unwrap();
|
||||
self.dir = match direction_s {
|
||||
"0" => Direction::Right,
|
||||
"1" => Direction::Down,
|
||||
"2" => Direction::Left,
|
||||
"3" => Direction::Up,
|
||||
s => panic!("`{}` is not a valid direction code", s),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct DigPlan {
|
||||
instructions: Vec<DigInstruction>,
|
||||
}
|
||||
|
||||
impl DigPlan {
|
||||
fn part2_transform(&mut self) {
|
||||
for i in &mut self.instructions {
|
||||
i.part2_transform();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct DigTile {
|
||||
position: Position,
|
||||
}
|
||||
|
||||
impl Default for DigTile {
|
||||
fn default() -> Self {
|
||||
Self { position: (0, 0) }
|
||||
}
|
||||
}
|
||||
|
||||
type Position = (isize, isize);
|
||||
|
||||
#[derive(Debug)]
|
||||
struct DigHole {
|
||||
tiles_loop: LinkedList<DigTile>,
|
||||
area: u64,
|
||||
}
|
||||
|
||||
// determinant of positions p1 and p2
|
||||
fn det(p1: Position, p2: Position) -> i64 {
|
||||
((p1.0 * p2.1) - (p1.1 * p2.0)) as i64
|
||||
}
|
||||
|
||||
impl DigHole {
|
||||
fn new() -> Self {
|
||||
DigHole {
|
||||
tiles_loop: LinkedList::new(),
|
||||
area: 0,
|
||||
}
|
||||
}
|
||||
fn pos_offset_n(&self, pos: Position, offset: (isize, isize), n: usize) -> Position {
|
||||
(pos.0 + offset.0 * n as isize, pos.1 + offset.1 * n as isize)
|
||||
}
|
||||
fn run_plan(&mut self, plan: &DigPlan) {
|
||||
let mut cur_pos = (0, 0);
|
||||
|
||||
self.tiles_loop.push_back(DigTile { position: cur_pos });
|
||||
let mut move_offset;
|
||||
for (idx, i) in plan.instructions.iter().enumerate() {
|
||||
let prev_instruction = if idx > 0 {
|
||||
&plan.instructions[idx - 1]
|
||||
} else {
|
||||
&plan.instructions[plan.instructions.len() - 1]
|
||||
};
|
||||
let Some(next_instruction) = plan.instructions.get(idx + 1).or(Some(&plan.instructions[0])) else {
|
||||
panic!()
|
||||
};
|
||||
let cur_turn = prev_instruction.dir.turn_kind(i.dir);
|
||||
let next_turn = i.dir.turn_kind(next_instruction.dir);
|
||||
|
||||
// Point needs to live on the 'outside' corner of the character. to achieve this we need to offset the move
|
||||
// by the following. Found this empirically but there's probably some mathematical principle behind it...
|
||||
move_offset = match (cur_turn, next_turn) {
|
||||
(Turn::RightNinety, Turn::RightNinety) => 1,
|
||||
(Turn::RightNinety, Turn::LeftNinety) => 0,
|
||||
(Turn::LeftNinety, Turn::LeftNinety) => -1,
|
||||
(Turn::LeftNinety, Turn::RightNinety) => 0,
|
||||
t => panic!("turn {:?} not allowed here", t),
|
||||
};
|
||||
|
||||
cur_pos = self.pos_offset_n(cur_pos, i.dir.offset(), (i.count as isize + move_offset) as usize);
|
||||
self.tiles_loop.push_back(DigTile { position: cur_pos });
|
||||
}
|
||||
|
||||
// Shoelace formula
|
||||
// https://en.wikipedia.org/wiki/Shoelace_formula
|
||||
let double_area: i64 = self
|
||||
.tiles_loop
|
||||
.iter()
|
||||
.tuple_windows()
|
||||
.map(|(a, b)| det(a.position, b.position))
|
||||
.sum();
|
||||
self.area = (double_area / 2).abs() as u64;
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Lines<'_>> for DigPlan {
|
||||
fn from(lines: Lines<'_>) -> Self {
|
||||
Self {
|
||||
instructions: lines.map(|line| DigInstruction::from(line)).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// PROBLEM 1 solution
|
||||
#[aoc(day18, part1)]
|
||||
fn part1(input: &str) -> u64 {
|
||||
let plan = DigPlan::from(input.lines());
|
||||
let mut dig = DigHole::new();
|
||||
dig.run_plan(&plan);
|
||||
dig.area
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
#[aoc(day18, part2)]
|
||||
fn part2(input: &str) -> u64 {
|
||||
let mut plan = DigPlan::from(input.lines());
|
||||
let mut dig = DigHole::new();
|
||||
plan.part2_transform();
|
||||
dig.run_plan(&plan);
|
||||
dig.area
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "R 6 (#70c710)
|
||||
D 5 (#0dc571)
|
||||
L 2 (#5713f0)
|
||||
D 2 (#d2c081)
|
||||
R 2 (#59c680)
|
||||
D 2 (#411b91)
|
||||
L 5 (#8ceee2)
|
||||
U 2 (#caa173)
|
||||
L 1 (#1b58a2)
|
||||
U 2 (#caa171)
|
||||
R 2 (#7807d2)
|
||||
U 3 (#a77fa3)
|
||||
L 2 (#015232)
|
||||
U 2 (#7a21e3)";
|
||||
|
||||
const AREA16_SQUARE: &str = "R 3 (#000000)
|
||||
D 3 (#000000)
|
||||
L 3 (#000000)
|
||||
U 4 (#000000";
|
||||
|
||||
#[test]
|
||||
fn area16_square() {
|
||||
assert_eq!(part1(AREA16_SQUARE), 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(EXAMPLE), 62);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(EXAMPLE), 952408144115);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use num_traits::Num;
|
||||
use std::collections::HashMap;
|
||||
use std::ops::{Index, IndexMut, Range};
|
||||
|
||||
// DATA
|
||||
|
||||
const INPUT_RANGE: Range<u64> = 1..4001;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct RulePredicate {
|
||||
op: PredicateOperator,
|
||||
var: char,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum RuleAction {
|
||||
Terminate(bool),
|
||||
Jump(String),
|
||||
}
|
||||
|
||||
impl From<&str> for RuleAction {
|
||||
fn from(s: &str) -> Self {
|
||||
match s {
|
||||
"A" => Self::Terminate(true),
|
||||
"R" => Self::Terminate(false),
|
||||
s => Self::Jump(s.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Rule {
|
||||
pred: RulePredicate,
|
||||
action: RuleAction,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum PredicateOperator {
|
||||
Always,
|
||||
Lt(u64),
|
||||
Gt(u64),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct XmasRanges {
|
||||
ranges: [Vec<Range<u64>>; 4],
|
||||
}
|
||||
|
||||
impl XmasRanges {
|
||||
fn none() -> XmasRanges {
|
||||
Self {
|
||||
ranges: [vec![0..0], vec![0..0], vec![0..0], vec![0..0]],
|
||||
}
|
||||
}
|
||||
fn all() -> XmasRanges {
|
||||
Self {
|
||||
ranges: [
|
||||
vec![INPUT_RANGE],
|
||||
vec![INPUT_RANGE],
|
||||
vec![INPUT_RANGE],
|
||||
vec![INPUT_RANGE],
|
||||
],
|
||||
}
|
||||
}
|
||||
fn idx(c: char) -> usize {
|
||||
match c {
|
||||
'x' => 0,
|
||||
'm' => 1,
|
||||
'a' => 2,
|
||||
's' => 3,
|
||||
c => panic!("`{}` is not a valid xmas char", c),
|
||||
}
|
||||
}
|
||||
fn insert(&mut self, c: char, v: Vec<Range<u64>>) {
|
||||
self.ranges[Self::idx(c)] = v;
|
||||
}
|
||||
fn count_states(&self) -> u64 {
|
||||
self.ranges
|
||||
.iter()
|
||||
.map(|ranges| ranges.iter().map(|range| range.end - range.start).sum::<u64>())
|
||||
.product()
|
||||
}
|
||||
}
|
||||
|
||||
impl Index<char> for XmasRanges {
|
||||
type Output = Vec<Range<u64>>;
|
||||
fn index(&self, index: char) -> &Self::Output {
|
||||
&self.ranges[Self::idx(index)]
|
||||
}
|
||||
}
|
||||
|
||||
impl IndexMut<char> for XmasRanges {
|
||||
fn index_mut(&mut self, index: char) -> &mut Self::Output {
|
||||
&mut self.ranges[Self::idx(index)]
|
||||
}
|
||||
}
|
||||
|
||||
fn range_overlap<T: Num + Ord + Copy>(r1: &Range<T>, r2: &Range<T>) -> Option<Range<T>> {
|
||||
let new_start = std::cmp::max(r1.start, r2.start);
|
||||
let new_end = std::cmp::min(r1.end - T::one(), r2.end - T::one());
|
||||
|
||||
if new_start <= std::cmp::min(r1.end - T::one(), r2.end - T::one()) && new_end >= std::cmp::max(r1.start, r2.start)
|
||||
{
|
||||
Some(new_start..new_end + T::one())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn range_exclude<T: Num + Ord + Copy>(keep: &Range<T>, exclude: &Range<T>) -> Vec<Range<T>> {
|
||||
let mut residual = Vec::new();
|
||||
if let Some(overlap) = range_overlap(keep, exclude) {
|
||||
if keep.start < overlap.start {
|
||||
residual.push(keep.start..overlap.start);
|
||||
}
|
||||
if keep.end > overlap.end {
|
||||
residual.push(overlap.end..keep.end);
|
||||
}
|
||||
} else {
|
||||
residual.push(keep.clone());
|
||||
}
|
||||
residual
|
||||
}
|
||||
|
||||
impl From<&str> for PredicateOperator {
|
||||
fn from(s: &str) -> Self {
|
||||
let (op_s, val_s) = s.split_at(1);
|
||||
match op_s {
|
||||
"<" => PredicateOperator::Lt(val_s.parse().unwrap()),
|
||||
">" => PredicateOperator::Gt(val_s.parse().unwrap()),
|
||||
s => panic!("unknown operator {}", s),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for RulePredicate {
|
||||
fn from(s: &str) -> Self {
|
||||
let (var_s, pred_s) = s.split_at(1);
|
||||
Self {
|
||||
op: pred_s.into(),
|
||||
var: var_s.chars().next().unwrap(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RulePredicate {
|
||||
fn check(&self, part: &Part) -> bool {
|
||||
match self.op {
|
||||
PredicateOperator::Always => true,
|
||||
PredicateOperator::Gt(val) => part.0[&self.var] > val,
|
||||
PredicateOperator::Lt(val) => part.0[&self.var] < val,
|
||||
}
|
||||
}
|
||||
fn matching_range(&self) -> Range<u64> {
|
||||
match self.op {
|
||||
PredicateOperator::Always => INPUT_RANGE,
|
||||
PredicateOperator::Gt(val) => val + 1..INPUT_RANGE.end,
|
||||
PredicateOperator::Lt(val) => INPUT_RANGE.start..val,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for Rule {
|
||||
fn from(s: &str) -> Self {
|
||||
if let Some((predicate_s, action_s)) = s.split_once(':') {
|
||||
Self {
|
||||
pred: predicate_s.into(),
|
||||
action: action_s.into(),
|
||||
}
|
||||
} else {
|
||||
Self {
|
||||
pred: RulePredicate {
|
||||
op: PredicateOperator::Always,
|
||||
var: '\0',
|
||||
},
|
||||
action: s.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Rule {
|
||||
fn predicate_result(&self, ranges: XmasRanges) -> (XmasRanges, XmasRanges) {
|
||||
if let PredicateOperator::Always = self.pred.op {
|
||||
(ranges, XmasRanges::none())
|
||||
} else {
|
||||
let (mut matching, mut unmatching) = (ranges.clone(), ranges.clone());
|
||||
let relevant_ranges = &ranges[self.pred.var];
|
||||
matching.insert(
|
||||
self.pred.var,
|
||||
relevant_ranges
|
||||
.iter()
|
||||
.filter_map(|range| range_overlap(range, &self.pred.matching_range()))
|
||||
.collect(),
|
||||
);
|
||||
unmatching.insert(
|
||||
self.pred.var,
|
||||
relevant_ranges
|
||||
.iter()
|
||||
.flat_map(|range| range_exclude(range, &self.pred.matching_range()))
|
||||
.collect(),
|
||||
);
|
||||
(matching, unmatching)
|
||||
}
|
||||
}
|
||||
fn possible_ranges(&self, wfs: &Workflows, ranges: XmasRanges) -> (u64, XmasRanges) {
|
||||
let (matching, unmatching) = self.predicate_result(ranges);
|
||||
match &self.action {
|
||||
RuleAction::Terminate(true) => (matching.count_states(), unmatching),
|
||||
RuleAction::Terminate(false) => (0, unmatching),
|
||||
RuleAction::Jump(wf) => (wfs.0[wf].possible_ranges(wfs, matching), unmatching),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Workflow {
|
||||
name: String,
|
||||
rules: Vec<Rule>,
|
||||
}
|
||||
|
||||
impl From<&str> for Workflow {
|
||||
fn from(s: &str) -> Self {
|
||||
let (name_s, rest_s) = s.split_once('{').unwrap();
|
||||
let rules = rest_s.split_once('}').unwrap().0.split(',').map(|r| r.into()).collect();
|
||||
Self {
|
||||
name: name_s.into(),
|
||||
rules,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Workflow {
|
||||
fn execute(&self, part: &Part) -> RuleAction {
|
||||
for r in &self.rules {
|
||||
if r.pred.check(part) {
|
||||
return r.action.clone();
|
||||
}
|
||||
}
|
||||
panic!("unhandled part {:?}", part);
|
||||
}
|
||||
fn possible_ranges(&self, wfs: &Workflows, mut ranges: XmasRanges) -> u64 {
|
||||
let mut accum = 0u64;
|
||||
for r in &self.rules {
|
||||
let count;
|
||||
(count, ranges) = r.possible_ranges(wfs, ranges);
|
||||
accum += count
|
||||
}
|
||||
accum
|
||||
}
|
||||
}
|
||||
|
||||
impl Workflows {
|
||||
fn execute(&self, part: &Part) -> bool {
|
||||
let mut action = RuleAction::Jump("in".into());
|
||||
loop {
|
||||
match &action {
|
||||
RuleAction::Terminate(b) => return *b,
|
||||
RuleAction::Jump(j) => {
|
||||
let next_workflow = &self.0[j];
|
||||
action = next_workflow.execute(part)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn count_possible_states(&self) -> u64 {
|
||||
self.0["in".into()].possible_ranges(self, XmasRanges::all())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Workflows(HashMap<String, Workflow>);
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Part(HashMap<char, u64>);
|
||||
|
||||
impl From<&str> for Part {
|
||||
fn from(s: &str) -> Self {
|
||||
let (_, vars_s) = s.split_once('{').unwrap();
|
||||
let vars = vars_s.split_once('}').unwrap().0.split(',');
|
||||
let mut part = HashMap::new();
|
||||
for var in vars {
|
||||
let (name, val) = var.split_once('=').unwrap();
|
||||
part.insert(name.chars().next().unwrap(), val.parse().unwrap());
|
||||
}
|
||||
Self(part)
|
||||
}
|
||||
}
|
||||
|
||||
type Parts = Vec<Part>;
|
||||
|
||||
// PROBLEM 1 solution
|
||||
|
||||
#[aoc_generator(day19)]
|
||||
fn parse(input: &str) -> (Workflows, Parts) {
|
||||
let mut input = input.lines();
|
||||
let mut wfs = Workflows(HashMap::new());
|
||||
let mut parts: Parts = Vec::new();
|
||||
while let Some(line) = input.next() {
|
||||
if line != "" {
|
||||
let wf: Workflow = line.into();
|
||||
wfs.0.insert(wf.name.clone(), wf);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
while let Some(line) = input.next() {
|
||||
parts.push(line.into());
|
||||
}
|
||||
|
||||
(wfs, parts)
|
||||
}
|
||||
|
||||
#[aoc(day19, part1)]
|
||||
fn part1((wfs, parts): &(Workflows, Parts)) -> u64 {
|
||||
parts
|
||||
.iter()
|
||||
.filter(|part| wfs.execute(part))
|
||||
.map(|part| part.0.values().sum::<u64>())
|
||||
.sum::<u64>()
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
#[aoc(day19, part2)]
|
||||
fn part2((wfs, _): &(Workflows, Parts)) -> u64 {
|
||||
wfs.count_possible_states()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
const EXAMPLE: &str = "px{a<2006:qkq,m>2090:A,rfg}
|
||||
pv{a>1716:R,A}
|
||||
lnx{m>1548:A,A}
|
||||
rfg{s<537:gd,x>2440:R,A}
|
||||
qs{s>3448:A,lnx}
|
||||
qkq{x<1416:A,crn}
|
||||
crn{x>2662:A,R}
|
||||
in{s<1351:px,qqz}
|
||||
qqz{s>2770:qs,m<1801:hdj,R}
|
||||
gd{a>3333:R,R}
|
||||
hdj{m>838:A,pv}
|
||||
|
||||
{x=787,m=2655,a=1222,s=2876}
|
||||
{x=1679,m=44,a=2067,s=496}
|
||||
{x=2036,m=264,a=79,s=2244}
|
||||
{x=2461,m=1339,a=466,s=291}
|
||||
{x=2127,m=1623,a=2188,s=1013}";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(&parse(EXAMPLE)), 19114);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(&parse(EXAMPLE)), 167409079868000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
use aoc_runner_derive::aoc;
|
||||
use lazy_regex::{lazy_regex, Lazy};
|
||||
use regex::Regex;
|
||||
|
||||
// --- Day 2: Cube Conundrum ---
|
||||
|
||||
// You're launched high into the atmosphere! The apex of your trajectory just barely
|
||||
// reaches the surface of a large island floating in the sky. You gently land in a
|
||||
// fluffy pile of leaves. It's quite cold, but you don't see much snow. An Elf runs over
|
||||
// to greet you.
|
||||
|
||||
// The Elf explains that you've arrived at Snow Island and apologizes for the lack of
|
||||
// snow. He'll be happy to explain the situation, but it's a bit of a walk, so you have
|
||||
// some time. They don't get many visitors up here; would you like to play a game in the
|
||||
// meantime?
|
||||
|
||||
// As you walk, the Elf shows you a small bag and some cubes which are either red,
|
||||
// green, or blue. Each time you play this game, he will hide a secret number of cubes
|
||||
// of each color in the bag, and your goal is to figure out information about the number
|
||||
// of cubes.
|
||||
|
||||
// To get information, once a bag has been loaded with cubes, the Elf will reach into
|
||||
// the bag, grab a handful of random cubes, show them to you, and then put them back in
|
||||
// the bag. He'll do this a few times per game.
|
||||
|
||||
// You play several games and record the information from each game (your puzzle input).
|
||||
// Each game is listed with its ID number (like the 11 in Game 11: ...) followed by a
|
||||
// semicolon-separated list of subsets of cubes that were revealed from the bag (like 3
|
||||
// red, 5 green, 4 blue).
|
||||
|
||||
// For example, the record of a few games might look like this:
|
||||
|
||||
// Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green Game 2: 1 blue, 2 green; 3
|
||||
// green, 4 blue, 1 red; 1 green, 1 blue Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red,
|
||||
// 13 green; 5 green, 1 red Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15
|
||||
// blue, 14 red Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green
|
||||
|
||||
// In game 1, three sets of cubes are revealed from the bag (and then put back again).
|
||||
// The first set is 3 blue cubes and 4 red cubes; the second set is 1 red cube, 2 green
|
||||
// cubes, and 6 blue cubes; the third set is only 2 green cubes.
|
||||
|
||||
// PARSING
|
||||
|
||||
struct CubeCount {
|
||||
blue: u64,
|
||||
red: u64,
|
||||
green: u64,
|
||||
}
|
||||
|
||||
impl Default for CubeCount {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
blue: 0,
|
||||
red: 0,
|
||||
green: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for CubeCount {
|
||||
fn from(s: &str) -> Self {
|
||||
let mut result = Self::default();
|
||||
let counts = s.split(", ");
|
||||
for count in counts {
|
||||
let (n, color) = count.split_once(' ').unwrap();
|
||||
match color {
|
||||
"blue" => result.blue = n.parse().unwrap(),
|
||||
"red" => result.red = n.parse().unwrap(),
|
||||
"green" => result.green = n.parse().unwrap(),
|
||||
_ => panic!("bad colour {}", color),
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
pub static GAME_ID_REGEX: Lazy<Regex> = lazy_regex!(r"^Game ([0-9]+)");
|
||||
|
||||
struct GameResult {
|
||||
id: u64,
|
||||
results: Vec<CubeCount>,
|
||||
}
|
||||
|
||||
impl From<&str> for GameResult {
|
||||
fn from(s: &str) -> Self {
|
||||
let mut results = Vec::new();
|
||||
let (s_id, rest) = s.split_once(": ").unwrap();
|
||||
let id: u64 = GAME_ID_REGEX
|
||||
.captures(s_id)
|
||||
.unwrap()
|
||||
.get(1)
|
||||
.unwrap()
|
||||
.as_str()
|
||||
.parse()
|
||||
.unwrap();
|
||||
|
||||
let s_results = rest.split("; ");
|
||||
|
||||
for s_result in s_results {
|
||||
results.push(CubeCount::from(s_result));
|
||||
}
|
||||
|
||||
GameResult { id, results }
|
||||
}
|
||||
}
|
||||
|
||||
// PROBLEM 1 solution
|
||||
|
||||
// The Elf would first like to know which games would have been possible if the bag
|
||||
// contained only 12 red cubes, 13 green cubes, and 14 blue cubes?
|
||||
|
||||
// In the example above, games 1, 2, and 5 would have been possible if the bag had been
|
||||
// loaded with that configuration. However, game 3 would have been impossible because at
|
||||
// one point the Elf showed you 20 red cubes at once; similarly, game 4 would also have
|
||||
// been impossible because the Elf showed you 15 blue cubes at once. If you add up the
|
||||
// IDs of the games that would have been possible, you get 8.
|
||||
|
||||
// Determine which games would have been possible if the bag had been loaded with only
|
||||
// 12 red cubes, 13 green cubes, and 14 blue cubes. What is the sum of the IDs of those
|
||||
// games?
|
||||
|
||||
// possible criteria: 12 red cubes, 13 green cubes, and 14 blue cubes
|
||||
|
||||
const PROBLEM1_MINIMUM: CubeCount = CubeCount {
|
||||
red: 12,
|
||||
green: 13,
|
||||
blue: 14,
|
||||
};
|
||||
|
||||
fn problem1_result_possible(game: &GameResult) -> bool {
|
||||
!game.results.iter().any(|result| {
|
||||
result.red > PROBLEM1_MINIMUM.red
|
||||
|| result.green > PROBLEM1_MINIMUM.green
|
||||
|| result.blue > PROBLEM1_MINIMUM.blue
|
||||
})
|
||||
}
|
||||
|
||||
#[aoc(day2, part1)]
|
||||
fn part1(input: &str) -> u64 {
|
||||
let mut n = 0u64;
|
||||
for line in input.lines() {
|
||||
let game_result = GameResult::from(line);
|
||||
if problem1_result_possible(&game_result) {
|
||||
n += game_result.id;
|
||||
}
|
||||
}
|
||||
|
||||
n
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
|
||||
// --- Part Two ---
|
||||
|
||||
// The Elf says they've stopped producing snow because they aren't getting any water! He
|
||||
// isn't sure why the water stopped; however, he can show you how to get to the water
|
||||
// source to check it out for yourself. It's just up ahead!
|
||||
|
||||
// As you continue your walk, the Elf poses a second question: in each game you played,
|
||||
// what is the fewest number of cubes of each color that could have been in the bag to
|
||||
// make the game possible?
|
||||
|
||||
// Again consider the example games from earlier:
|
||||
|
||||
// Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green Game 2: 1 blue, 2 green; 3
|
||||
// green, 4 blue, 1 red; 1 green, 1 blue Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red,
|
||||
// 13 green; 5 green, 1 red Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15
|
||||
// blue, 14 red Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green
|
||||
|
||||
// In game 1, the game could have been played with as few as 4 red, 2 green, and 6
|
||||
// blue cubes. If any color had even one fewer cube, the game would have been
|
||||
// impossible. Game 2 could have been played with a minimum of 1 red, 3 green, and 4
|
||||
// blue cubes. Game 3 must have been played with at least 20 red, 13 green, and 6
|
||||
// blue cubes. Game 4 required at least 14 red, 3 green, and 15 blue cubes. Game 5
|
||||
// needed no fewer than 6 red, 3 green, and 2 blue cubes in the bag.
|
||||
|
||||
// The power of a set of cubes is equal to the numbers of red, green, and blue cubes
|
||||
// multiplied together. The power of the minimum set of cubes in game 1 is 48. In games
|
||||
// 2-5 it was 12, 1560, 630, and 36, respectively. Adding up these five powers produces
|
||||
// the sum 2286.
|
||||
|
||||
// For each game, find the minimum set of cubes that must have been present. What is the
|
||||
// sum of the power of these sets?
|
||||
|
||||
// Minimum power = maximum seen of each colour across all games, r * g * b
|
||||
fn problem2_game_minimum_power(game: &GameResult) -> u64 {
|
||||
// Could be done in one pass, but this is cleaner using Iter methods
|
||||
let max_r = game.results.iter().map(|c| c.red).max().unwrap();
|
||||
let max_g = game.results.iter().map(|c| c.green).max().unwrap();
|
||||
let max_b = game.results.iter().map(|c| c.blue).max().unwrap();
|
||||
|
||||
max_r * max_g * max_b
|
||||
}
|
||||
|
||||
#[aoc(day2, part2)]
|
||||
fn part2(input: &str) -> u64 {
|
||||
let games = input.lines().map(|l| GameResult::from(l));
|
||||
games.fold(0u64, |accum, val| accum + problem2_game_minimum_power(&val))
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
use aoc_runner_derive::aoc;
|
||||
use std::collections::{BinaryHeap, HashMap, VecDeque};
|
||||
use std::fmt::Display;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::str::Lines;
|
||||
|
||||
use lazy_regex::lazy_regex;
|
||||
use num::integer::lcm;
|
||||
|
||||
// PARSE
|
||||
|
||||
const MODULE_PATTERN: lazy_regex::Lazy<lazy_regex::Regex> = lazy_regex!("^([%&]?)([a-z]+) -> ([a-z, ]+)$");
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
|
||||
enum PulseType {
|
||||
Low,
|
||||
High,
|
||||
}
|
||||
|
||||
impl From<bool> for PulseType {
|
||||
fn from(value: bool) -> Self {
|
||||
match value {
|
||||
true => PulseType::High,
|
||||
false => PulseType::Low,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PulseType> for bool {
|
||||
fn from(value: PulseType) -> Self {
|
||||
match value {
|
||||
PulseType::High => true,
|
||||
PulseType::Low => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for PulseType {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
PulseType::Low => f.write_str("low"),
|
||||
PulseType::High => f.write_str("high"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum ModuleKind {
|
||||
FlipFlop,
|
||||
Conjunction,
|
||||
Broadcast,
|
||||
Button,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Module {
|
||||
name: String,
|
||||
kind: Option<ModuleKind>,
|
||||
inputs: Vec<String>,
|
||||
outputs: Vec<String>,
|
||||
on: bool,
|
||||
last_input_states: Vec<PulseType>,
|
||||
}
|
||||
|
||||
impl Hash for Module {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
// the only states that change are 'on' and 'last_input_states', the rest are constant once created
|
||||
self.on.hash(state);
|
||||
self.last_input_states.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl Module {
|
||||
fn new(name: String) -> Self {
|
||||
Self {
|
||||
name,
|
||||
kind: None,
|
||||
inputs: Vec::new(),
|
||||
outputs: Vec::new(),
|
||||
on: false,
|
||||
last_input_states: Vec::new(),
|
||||
}
|
||||
}
|
||||
fn source_idx(&self, name: &str) -> usize {
|
||||
self.inputs.iter().position(|in_name| in_name == name).unwrap()
|
||||
}
|
||||
fn with_kind(name: String, kind: ModuleKind) -> Self {
|
||||
let mut m = Self::new(name);
|
||||
m.kind = Some(kind);
|
||||
m
|
||||
}
|
||||
fn and_destinations(mut self, destinations: &str) -> Self {
|
||||
for dest in destinations.split(", ") {
|
||||
self.outputs.push(dest.into());
|
||||
}
|
||||
self
|
||||
}
|
||||
fn and_source(mut self, source: String) -> Self {
|
||||
self.add_source(source);
|
||||
self
|
||||
}
|
||||
fn add_source(&mut self, source: String) {
|
||||
self.inputs.push(source);
|
||||
self.last_input_states.push(PulseType::Low);
|
||||
}
|
||||
fn reset(&mut self) {
|
||||
// relevant state is on and last_input_states
|
||||
self.on = false;
|
||||
for input in &mut self.last_input_states {
|
||||
*input = PulseType::Low;
|
||||
}
|
||||
}
|
||||
#[allow(unused)]
|
||||
fn state_space(&self) -> u128 {
|
||||
match self.kind {
|
||||
Some(ModuleKind::Broadcast) | Some(ModuleKind::Button) => 1,
|
||||
Some(ModuleKind::FlipFlop) => 2,
|
||||
Some(ModuleKind::Conjunction) => 1 << self.last_input_states.len(), // 2^n
|
||||
None => 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for Module {
|
||||
fn from(s: &str) -> Self {
|
||||
let Some(re_result) = MODULE_PATTERN.captures(s) else {
|
||||
panic!("unparseable module: {}", s);
|
||||
};
|
||||
let (_, [kind, name, destinations]) = re_result.extract();
|
||||
if name == "broadcaster" {
|
||||
return Module::with_kind(name.into(), ModuleKind::Broadcast).and_destinations(destinations);
|
||||
};
|
||||
match kind {
|
||||
"%" => Module::with_kind(name.into(), ModuleKind::FlipFlop).and_destinations(destinations),
|
||||
"&" => Module::with_kind(name.into(), ModuleKind::Conjunction).and_destinations(destinations),
|
||||
_ => panic!("invalid module kind {}", kind),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Job {
|
||||
signal: PulseType,
|
||||
targets: Vec<String>,
|
||||
from: String,
|
||||
priority: usize,
|
||||
}
|
||||
|
||||
impl PartialEq for Job {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.priority == other.priority
|
||||
}
|
||||
}
|
||||
impl Eq for Job {}
|
||||
|
||||
impl PartialOrd for Job {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
other.priority.partial_cmp(&self.priority)
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for Job {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
self.partial_cmp(other).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Machine {
|
||||
modules: HashMap<String, Module>,
|
||||
work_queue: BinaryHeap<Job>,
|
||||
count_low: u64,
|
||||
count_high: u64,
|
||||
}
|
||||
|
||||
impl From<Lines<'_>> for Machine {
|
||||
fn from(mut lines: Lines<'_>) -> Self {
|
||||
let mut modules = HashMap::from([(
|
||||
"button".into(),
|
||||
Module::with_kind("button".into(), ModuleKind::Button).and_destinations("broadcaster"),
|
||||
)]);
|
||||
while let Some(line) = lines.next() {
|
||||
let mut module = Module::from(line);
|
||||
for output in &module.outputs {
|
||||
if let Some(output_mod) = modules.get_mut(output) {
|
||||
// already exists, push to input list
|
||||
output_mod.add_source(module.name.to_owned());
|
||||
} else {
|
||||
// forward declaration of 'unknown' modules
|
||||
modules.insert(
|
||||
output.clone(),
|
||||
Module::new(output.clone()).and_source(module.name.clone()),
|
||||
);
|
||||
}
|
||||
}
|
||||
if let Some(existing_mod) = modules.get(&module.name) {
|
||||
module.inputs = existing_mod.inputs.clone(); // might have been pre-prepared, the rest we take ours
|
||||
module.last_input_states = existing_mod.last_input_states.clone();
|
||||
}
|
||||
modules.insert(module.name.clone(), module);
|
||||
}
|
||||
|
||||
Machine {
|
||||
modules,
|
||||
work_queue: BinaryHeap::new(),
|
||||
count_low: 0,
|
||||
count_high: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Machine {
|
||||
fn press_button(&mut self) {
|
||||
self.send_pulse(PulseType::Low, "broadcaster", "button", 1);
|
||||
}
|
||||
fn send_pulse(&mut self, signal: PulseType, target: &str, from: &str, priority: usize) {
|
||||
// count pulse when it is received
|
||||
match signal {
|
||||
PulseType::Low => self.count_low += 1,
|
||||
PulseType::High => self.count_high += 1,
|
||||
};
|
||||
match self.modules[target].kind {
|
||||
Some(ModuleKind::Button) | Some(ModuleKind::Broadcast) => {
|
||||
self.send_all_outputs(PulseType::Low, target, priority)
|
||||
}
|
||||
Some(ModuleKind::FlipFlop) => match signal {
|
||||
PulseType::High => (),
|
||||
PulseType::Low => {
|
||||
let new_state = !self.modules.get_mut(target).unwrap().on;
|
||||
self.modules.get_mut(target).unwrap().on = new_state;
|
||||
self.send_all_outputs(new_state.into(), target, priority)
|
||||
}
|
||||
},
|
||||
Some(ModuleKind::Conjunction) => {
|
||||
let target_m = self.modules.get_mut(target).unwrap();
|
||||
let source_idx = target_m.source_idx(from);
|
||||
target_m.last_input_states[source_idx] = signal;
|
||||
if target_m.last_input_states.iter().all(|state| *state == PulseType::High) {
|
||||
self.send_all_outputs(PulseType::Low, target, priority)
|
||||
} else {
|
||||
self.send_all_outputs(PulseType::High, target, priority)
|
||||
}
|
||||
}
|
||||
None => (),
|
||||
}
|
||||
}
|
||||
fn send_all_outputs(&mut self, signal: PulseType, from: &str, priority: usize) {
|
||||
self.work_queue.push(Job {
|
||||
signal,
|
||||
targets: self.modules[from].outputs.iter().map(|op| op.to_owned()).collect(),
|
||||
from: from.to_owned(),
|
||||
priority: priority + 1,
|
||||
})
|
||||
}
|
||||
fn run(&mut self) {
|
||||
while let Some(job) = self.work_queue.pop() {
|
||||
for target in job.targets {
|
||||
self.send_pulse(job.signal, &target, &job.from, job.priority);
|
||||
}
|
||||
}
|
||||
}
|
||||
// the number of cycles it took until the target sends a low pulse, or None if the target node sent no low pulses but the job finished
|
||||
fn time_to_state(&mut self, goal: &str, state: PulseType) -> Option<u64> {
|
||||
while let Some(job) = self.work_queue.pop() {
|
||||
if job.from == goal && job.signal == state {
|
||||
return Some(self.count_high + self.count_low);
|
||||
}
|
||||
for target in job.targets {
|
||||
self.send_pulse(job.signal, &target, &job.from, job.priority);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
fn reset(&mut self) {
|
||||
for (_name, m) in &mut self.modules {
|
||||
m.reset();
|
||||
}
|
||||
self.count_low = 0;
|
||||
self.count_high = 0;
|
||||
}
|
||||
#[allow(unused)]
|
||||
fn state_space(&self) -> u128 {
|
||||
self.modules.values().map(|m| m.state_space()).product()
|
||||
}
|
||||
}
|
||||
|
||||
// PROBLEM 1 solution
|
||||
const PROBLEM1_ITERATIONS: usize = 1000;
|
||||
#[aoc(day20, part1)]
|
||||
fn part1(input: &str) -> u64 {
|
||||
let mut machine = Machine::from(input.lines());
|
||||
for _ in 0..PROBLEM1_ITERATIONS {
|
||||
machine.press_button();
|
||||
machine.run();
|
||||
}
|
||||
machine.count_low * machine.count_high
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
#[aoc(day20, part2)]
|
||||
#[allow(unused)]
|
||||
fn part2(input: &str) -> u128 {
|
||||
let mut machine = Machine::from(input.lines());
|
||||
// println!("STATES: {}", machine.state_space());
|
||||
// Find the rx module and look at its parent(s)
|
||||
let rx = &machine.modules["rx"];
|
||||
// my input has a single conjunction as parent, todo implement other possibilities
|
||||
let con = &machine.modules[&rx.inputs[0]];
|
||||
|
||||
// for each input, find how long it takes for it to be High, so the conjunction sends a low to rx
|
||||
let mut cycles: Vec<_> = Vec::new();
|
||||
for input in con.inputs.clone() {
|
||||
// print!("searching distance to {}...", input);
|
||||
machine.reset();
|
||||
let mut button_count = 0;
|
||||
loop {
|
||||
machine.press_button();
|
||||
button_count += 1;
|
||||
if let Some(distance) = machine.time_to_state(&input, PulseType::High) {
|
||||
// println!("got {} pulses, {} button presses", distance, button_count);
|
||||
cycles.push(button_count as u128);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
cycles.iter().fold(1, |accum, cycle| lcm(accum, *cycle))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "broadcaster -> a
|
||||
%a -> inv, con
|
||||
&inv -> b
|
||||
%b -> con
|
||||
&con -> output";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(EXAMPLE), 11687500);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
use aoc_runner_derive::aoc;
|
||||
use core::panic;
|
||||
use indicatif::{ProgressBar, ProgressStyle};
|
||||
use rayon::prelude::*;
|
||||
use std::collections::HashSet;
|
||||
use std::str::Lines;
|
||||
|
||||
// PARSE
|
||||
|
||||
type Position = (isize, isize);
|
||||
type WrappedPosition = (usize, usize);
|
||||
type Offset = (isize, isize);
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct MapTile {
|
||||
c: char,
|
||||
}
|
||||
|
||||
impl MapTile {
|
||||
fn new(c: char) -> Self {
|
||||
Self { c }
|
||||
}
|
||||
}
|
||||
|
||||
struct GardenMap {
|
||||
map: Vec<Vec<MapTile>>,
|
||||
start: Position,
|
||||
}
|
||||
|
||||
impl From<Lines<'_>> for GardenMap {
|
||||
fn from(lines: Lines<'_>) -> Self {
|
||||
let map = lines
|
||||
.map(|line| line.chars().map(|c| MapTile::new(c)).collect())
|
||||
.collect();
|
||||
let mut new = Self { map, start: (0, 0) };
|
||||
new.find_start();
|
||||
new
|
||||
}
|
||||
}
|
||||
|
||||
const ADJACENCIES: [Offset; 4] = [(-1, 0), (1, 0), (0, -1), (0, 1)];
|
||||
|
||||
impl GardenMap {
|
||||
fn wrap_pos(&self, pos: &Position) -> WrappedPosition {
|
||||
let (width, height) = (self.width() as isize, self.height() as isize);
|
||||
(
|
||||
if pos.0 < 0 {
|
||||
(pos.0 + (-pos.0 / width + 1) * width) as usize % self.width()
|
||||
} else {
|
||||
pos.0 as usize % self.width()
|
||||
},
|
||||
if pos.1 < 0 {
|
||||
(pos.1 + (-pos.1 / height + 1) * height) as usize % self.height()
|
||||
} else {
|
||||
pos.1 as usize % self.height()
|
||||
},
|
||||
)
|
||||
}
|
||||
fn width(&self) -> usize {
|
||||
self.map[0].len()
|
||||
}
|
||||
fn height(&self) -> usize {
|
||||
self.map.len()
|
||||
}
|
||||
fn at(&self, pos: &Position) -> &MapTile {
|
||||
let pos = self.wrap_pos(pos);
|
||||
&self.map[pos.1][pos.0]
|
||||
}
|
||||
// return the valid 'moves' from pos
|
||||
fn adjacent_to(&self, pos: &Position) -> Vec<Position> {
|
||||
ADJACENCIES
|
||||
.iter()
|
||||
.filter_map(|ofs| self.offset_pos(pos, ofs))
|
||||
.filter(|pos| self.at(pos).c != '#')
|
||||
.collect()
|
||||
}
|
||||
fn offset_pos(&self, pos: &Position, ofs: &Offset) -> Option<Position> {
|
||||
let new_pos = (pos.0 as isize + ofs.0, pos.1 as isize + ofs.1);
|
||||
return Some((new_pos.0, new_pos.1));
|
||||
}
|
||||
fn find_start(&mut self) {
|
||||
for (y, row) in self.map.iter().enumerate() {
|
||||
for (x, tile) in row.iter().enumerate() {
|
||||
if tile.c == 'S' {
|
||||
self.start = (x as isize, y as isize);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
panic!("didn't find the start square!");
|
||||
}
|
||||
fn reachable_after(&self, from: &Position, n: usize) -> u64 {
|
||||
let bar = ProgressBar::new(n as u64).with_style(
|
||||
ProgressStyle::with_template(
|
||||
"[{elapsed_precise}/{eta_precise}] {bar:40.cyan/blue} {pos:>7}/{len:7} {per_sec}",
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
let mut visited_after: Vec<HashSet<Position>> = Vec::new();
|
||||
visited_after.push(HashSet::from([*from]));
|
||||
for i in 1..n + 1 {
|
||||
visited_after.push(
|
||||
visited_after[i - 1]
|
||||
.iter()
|
||||
.flat_map(|last| self.adjacent_to(last))
|
||||
.collect(),
|
||||
);
|
||||
bar.inc(1);
|
||||
// if primes::is_prime(i as u64) {
|
||||
// println!("count after {} steps: {}", i, visited_after[i].len());
|
||||
// }
|
||||
}
|
||||
|
||||
visited_after[n].len() as u64
|
||||
}
|
||||
fn reachable_count_after(&self, from: &Position, n: usize) -> u64 {
|
||||
let dim = self.width() as f64;
|
||||
let target_mod = (n % self.width()) as f64;
|
||||
let x_values: Vec<f64> = vec![target_mod, target_mod + dim, target_mod + 2. * dim];
|
||||
let y_values: Vec<f64> = x_values
|
||||
.iter()
|
||||
.map(|n| self.reachable_after(from, *n as usize) as f64)
|
||||
.collect();
|
||||
|
||||
let coeffs = polyfit_rs::polyfit_rs::polyfit(&x_values, &y_values, 2).unwrap();
|
||||
// println!("values: x: {:?} y: {:?}", x_values, y_values);
|
||||
// println!("coefficients: {:?}", coeffs);
|
||||
|
||||
let f_n = n as f64;
|
||||
let result = coeffs[0] + coeffs[1] * f_n + coeffs[2] * f_n.powf(2.0);
|
||||
|
||||
result.round() as u64
|
||||
}
|
||||
#[allow(unused)]
|
||||
fn draw_with_bounds(&self, from: &Position, to: &Position) {
|
||||
for row in from.1..to.1 + 1 {
|
||||
for col in from.0..to.0 + 1 {
|
||||
// print!("{}", self.at(&(col, row)).c);
|
||||
}
|
||||
// println!();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// fn print_visited(map: &GardenMap, visited: &Vec<Vec<bool>>) {
|
||||
// for (y, row) in visited.iter().enumerate() {
|
||||
// for (x, cell) in row.iter().enumerate() {
|
||||
// print!("{}", if *cell { 'O' } else { map.at(&(x, y)).c });
|
||||
// }
|
||||
// println!();
|
||||
// }
|
||||
// }
|
||||
|
||||
// PROBLEM 1 solution
|
||||
|
||||
fn problem1_impl(input: &str, n: usize) -> u64 {
|
||||
let map = GardenMap::from(input.lines());
|
||||
// println!("map: {:?} start: {:?}", map.map, &map.start);
|
||||
// map.draw_with_bounds(
|
||||
// &(-(map.width() as isize), -(map.height() as isize)),
|
||||
// &(map.width() as isize * 2 + 1, map.height() as isize * 2 + 1),
|
||||
// );
|
||||
map.reachable_count_after(&map.start, n)
|
||||
}
|
||||
|
||||
#[aoc(day21, part1)]
|
||||
fn part1(input: &str) -> u64 {
|
||||
problem1_impl(input, 64)
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
#[aoc(day21, part2)]
|
||||
fn part2(input: &str) -> u64 {
|
||||
problem1_impl(input, 26501365)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rstest::rstest;
|
||||
|
||||
const EXAMPLE: &str = "...........
|
||||
.....###.#.
|
||||
.###.##..#.
|
||||
..#.#...#..
|
||||
....#.#....
|
||||
.##..S####.
|
||||
.##..#...#.
|
||||
.......##..
|
||||
.##.#.####.
|
||||
.##..##.##.
|
||||
...........";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(problem1_impl(EXAMPLE, 6), 16);
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case(6, 16)]
|
||||
#[case(10, 50)]
|
||||
#[case(50, 1594)]
|
||||
#[case(100, 6536)]
|
||||
#[case(500, 167004)]
|
||||
fn part2_example(#[case] n: usize, #[case] expect: u64) {
|
||||
assert_eq!(problem1_impl(EXAMPLE, n), expect);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
use aoc_runner_derive::aoc;
|
||||
use itertools::Itertools;
|
||||
use ndarray::prelude::*;
|
||||
use petgraph::prelude::*;
|
||||
use petgraph::visit::{IntoNodeReferences, Walker};
|
||||
use std::collections::BinaryHeap;
|
||||
use std::fmt::{Display, Write};
|
||||
use std::str::FromStr;
|
||||
|
||||
// PARSE
|
||||
|
||||
#[derive(Hash, PartialEq, Eq, Clone, Debug)]
|
||||
struct Coord {
|
||||
x: usize,
|
||||
y: usize,
|
||||
z: usize,
|
||||
}
|
||||
|
||||
impl FromStr for Coord {
|
||||
type Err = Box<dyn std::error::Error>;
|
||||
fn from_str(value: &str) -> Result<Self, Self::Err> {
|
||||
let (x, y, z) = value.split(',').next_tuple().unwrap();
|
||||
Ok(Self {
|
||||
x: x.parse()?,
|
||||
y: y.parse()?,
|
||||
z: z.parse()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Hash, PartialEq, Eq)]
|
||||
struct BrickBlock {
|
||||
c1: Coord,
|
||||
c2: Coord,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for BrickBlock {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
writeln!(
|
||||
f,
|
||||
"[{},{},{} - {},{},{}]",
|
||||
self.c1.x, self.c1.y, self.c1.z, self.c2.x, self.c2.y, self.c2.z
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl BrickBlock {
|
||||
fn bottom_z_plane(&self) -> usize {
|
||||
std::cmp::min(self.c1.z, self.c2.z)
|
||||
}
|
||||
fn top_z_plane(&self) -> usize {
|
||||
std::cmp::max(self.c1.z, self.c2.z)
|
||||
}
|
||||
fn bottom_x_plane(&self) -> usize {
|
||||
std::cmp::min(self.c1.x, self.c2.x)
|
||||
}
|
||||
fn top_x_plane(&self) -> usize {
|
||||
std::cmp::max(self.c1.x, self.c2.x)
|
||||
}
|
||||
fn bottom_y_plane(&self) -> usize {
|
||||
std::cmp::min(self.c1.y, self.c2.y)
|
||||
}
|
||||
fn top_y_plane(&self) -> usize {
|
||||
std::cmp::max(self.c1.y, self.c2.y)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for BrickBlock {
|
||||
fn from(value: &str) -> Self {
|
||||
let (c1, c2) = value.split_once('~').unwrap();
|
||||
Self {
|
||||
c1: c1.parse().unwrap(),
|
||||
c2: c2.parse().unwrap(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for BrickBlock {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
Some(other.bottom_z_plane().cmp(&self.bottom_z_plane()))
|
||||
}
|
||||
}
|
||||
|
||||
// Note this is a reversed ordering
|
||||
impl Ord for BrickBlock {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
self.bottom_z_plane().cmp(&other.bottom_z_plane())
|
||||
}
|
||||
}
|
||||
|
||||
type BlockMap = Array3<MapTile>;
|
||||
type MapTile = Option<BrickBlock>;
|
||||
|
||||
struct BlockPile {
|
||||
blocks: Vec<BrickBlock>,
|
||||
block_map: Array3<MapTile>,
|
||||
bounds: (usize, usize, usize),
|
||||
graph: Graph<BrickBlock, (), Directed, usize>,
|
||||
}
|
||||
|
||||
impl BlockPile {
|
||||
fn remove_block(&mut self, block: &BrickBlock) {
|
||||
// loop over the (inclusive) bounding coordinates and remove them all from the map
|
||||
self.block_map
|
||||
.slice_mut(s![
|
||||
block.bottom_x_plane()..block.top_x_plane() + 1,
|
||||
block.bottom_y_plane()..block.top_y_plane() + 1,
|
||||
block.bottom_z_plane()..block.top_z_plane() + 1,
|
||||
])
|
||||
.fill(None);
|
||||
self.blocks.remove(self.blocks.iter().position(|b| b == block).unwrap());
|
||||
}
|
||||
fn add_block(&mut self, block: &BrickBlock) {
|
||||
// loop over the (inclusive) bounding coordinates and remove them all from the map
|
||||
self.block_map
|
||||
.slice_mut(s![
|
||||
block.bottom_x_plane()..block.top_x_plane() + 1,
|
||||
block.bottom_y_plane()..block.top_y_plane() + 1,
|
||||
block.bottom_z_plane()..block.top_z_plane() + 1,
|
||||
])
|
||||
.fill(Some(block.to_owned()));
|
||||
self.blocks.push(block.clone());
|
||||
}
|
||||
fn blocks_directly_above(&self, block: &BrickBlock) -> Vec<BrickBlock> {
|
||||
// find the top plane of the block
|
||||
// get the array range of all squares at z_plane + 1 within the bounds of x & y
|
||||
// i think there is a built in way in ndarray to do this...
|
||||
let directly_above = self.block_map.slice(s![
|
||||
block.bottom_x_plane()..block.top_x_plane() + 1,
|
||||
block.bottom_y_plane()..block.top_y_plane() + 1,
|
||||
block.top_z_plane() + 1..std::cmp::min(block.top_z_plane() + 2, self.bounds.2)
|
||||
]);
|
||||
|
||||
directly_above.iter().filter_map(|v| v.clone()).unique().collect()
|
||||
}
|
||||
fn supported_by(&self, block: &BrickBlock) -> usize {
|
||||
let z_plane = std::cmp::min(block.c1.z, block.c2.z);
|
||||
// get the slice of tiles below us
|
||||
let directly_below = self.block_map.slice(s![
|
||||
block.bottom_x_plane()..block.top_x_plane() + 1,
|
||||
block.bottom_y_plane()..block.top_y_plane() + 1,
|
||||
z_plane - 1..z_plane // the layer below
|
||||
]);
|
||||
directly_below.iter().filter_map(|v| v.clone()).unique().count()
|
||||
}
|
||||
fn blocks_above_will_move_if_we_are_gone(&mut self, block: &BrickBlock) -> bool {
|
||||
self.blocks_directly_above(&block)
|
||||
.iter()
|
||||
.map(|b| self.supported_by(b))
|
||||
.any(|b| b == 1) // block we support will move if we are their only support
|
||||
}
|
||||
fn blocks_supported_by_at_all(&self, block: &BrickBlock) -> Vec<BrickBlock> {
|
||||
self.blocks_directly_above(&block).iter().map(|b| b.clone()).collect()
|
||||
}
|
||||
/// Find the plane of the first block directly below us
|
||||
fn supporting_plane(&self, block: &BrickBlock) -> Option<usize> {
|
||||
// find the bottom plane of ourselves
|
||||
let z_plane = std::cmp::min(block.c1.z, block.c2.z);
|
||||
// get the slice of tiles below us
|
||||
let directly_below = self.block_map.slice(s![
|
||||
block.bottom_x_plane()..block.top_x_plane() + 1,
|
||||
block.bottom_y_plane()..block.top_y_plane() + 1,
|
||||
1..z_plane // don't include our own plane
|
||||
]);
|
||||
// find the highest top z value of those
|
||||
let block_below = directly_below
|
||||
.indexed_iter()
|
||||
.filter_map(|(idx, v)| if let Some(val) = v { Some((idx, val)) } else { None })
|
||||
.max_by_key(|(_idx, v)| v.top_z_plane());
|
||||
|
||||
if let Some(block) = block_below {
|
||||
Some(block.1.top_z_plane())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn drop_blocks(&mut self) {
|
||||
// VecDeque doesn't sort and Vec isn't convenient for pushback and popfront, so eh... use a heap.
|
||||
let mut blocks_to_move = BinaryHeap::from(self.blocks.clone());
|
||||
while let Some(mut block) = blocks_to_move.pop() {
|
||||
let z_move = match self.supporting_plane(&block) {
|
||||
Some(z) if z + 1 != block.bottom_z_plane() => block.bottom_z_plane() - (z + 1),
|
||||
None if block.bottom_z_plane() != 1 => block.bottom_z_plane() - 1,
|
||||
_ => {
|
||||
continue;
|
||||
} // we are in position already with nothing below us
|
||||
};
|
||||
self.remove_block(&block);
|
||||
block.c1.z -= z_move;
|
||||
block.c2.z -= z_move;
|
||||
self.add_block(&block);
|
||||
blocks_to_move.push(block);
|
||||
}
|
||||
}
|
||||
fn build_graph(&mut self) {
|
||||
self.blocks.sort_by_key(|b| b.bottom_z_plane());
|
||||
for b in 0..self.blocks.len() {
|
||||
self.graph.add_node(self.blocks[b].clone());
|
||||
}
|
||||
for b in 0..self.blocks.len() {
|
||||
let block = &self.blocks[b];
|
||||
let depends_on_us = self.blocks_supported_by_at_all(block);
|
||||
for dependent in depends_on_us {
|
||||
self.graph.add_edge(
|
||||
b.into(),
|
||||
self.blocks.iter().position(|b| b == &dependent).unwrap().into(),
|
||||
(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for BlockPile {
|
||||
fn from(input: &str) -> Self {
|
||||
let blocks = input.lines().map(|line| BrickBlock::from(line)).collect_vec();
|
||||
let mut bounds = (0, 0, 0);
|
||||
for block in &blocks {
|
||||
bounds.0 = std::cmp::max(block.top_x_plane() + 1, bounds.0);
|
||||
bounds.1 = std::cmp::max(block.top_y_plane() + 1, bounds.1);
|
||||
bounds.2 = std::cmp::max(block.top_z_plane() + 1, bounds.2);
|
||||
}
|
||||
let mut new = BlockPile {
|
||||
blocks: Vec::new(),
|
||||
bounds,
|
||||
block_map: BlockMap::from_elem(bounds, None),
|
||||
graph: Graph::default(),
|
||||
};
|
||||
for block in blocks {
|
||||
new.add_block(&block);
|
||||
}
|
||||
|
||||
new
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for BlockPile {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
for z in (0..self.bounds.2).rev() {
|
||||
let z_plane = self.block_map.slice(s![.., .., z..z + 1]);
|
||||
if z_plane.iter().all(|b| b.is_none()) {
|
||||
continue;
|
||||
};
|
||||
for i in 0..self.bounds.0 {
|
||||
// XZ view
|
||||
let y = z_plane.slice(s![i..i + 1, .., ..]);
|
||||
f.write_char(
|
||||
match y.iter().enumerate().find_map(|(idx, val)| val.is_some().then(|| idx)) {
|
||||
None => ' ',
|
||||
Some(0) | Some(1) => '█',
|
||||
Some(2) | Some(3) => '▓',
|
||||
Some(4) | Some(5) => '▒',
|
||||
Some(6) | Some(7) => '░',
|
||||
_ => '░',
|
||||
},
|
||||
)?;
|
||||
}
|
||||
write!(f, " {} ", z)?;
|
||||
for y in 0..self.bounds.1 {
|
||||
let x = z_plane.slice(s![.., y..y + 1, ..]);
|
||||
f.write_char(
|
||||
match x.iter().enumerate().find_map(|(idx, val)| val.is_some().then(|| idx)) {
|
||||
None => ' ',
|
||||
Some(0) | Some(1) => '█',
|
||||
Some(2) | Some(3) => '▓',
|
||||
Some(4) | Some(5) => '▒',
|
||||
Some(6) | Some(7) => '░',
|
||||
_ => '░',
|
||||
},
|
||||
)?;
|
||||
}
|
||||
writeln!(f, " {}", z)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// PROBLEM 1 solution
|
||||
|
||||
#[aoc(day22, part1)]
|
||||
fn part1(input: &str) -> u64 {
|
||||
let mut pile = BlockPile::from(input);
|
||||
// println!("{}", pile);
|
||||
// println!("dropping blocks!");
|
||||
pile.drop_blocks();
|
||||
// println!("{}", pile);
|
||||
|
||||
let blocks = pile.blocks.clone();
|
||||
let removable: Vec<_> = blocks
|
||||
.iter()
|
||||
.filter(|b| !pile.blocks_above_will_move_if_we_are_gone(*b))
|
||||
.collect();
|
||||
|
||||
removable.len() as u64
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
#[aoc(day22, part2)]
|
||||
fn part2(input: &str) -> u64 {
|
||||
let mut pile = BlockPile::from(input);
|
||||
pile.drop_blocks();
|
||||
pile.build_graph();
|
||||
|
||||
// println!("{}", pile);
|
||||
|
||||
let mut accum = 0;
|
||||
let fixed_nodes = pile
|
||||
.graph
|
||||
.node_references()
|
||||
.filter(|(_idx, b)| b.bottom_z_plane() == 1)
|
||||
.map(|(idx, _b)| idx)
|
||||
.collect_vec();
|
||||
for node in pile.graph.node_indices() {
|
||||
// remove links to node's neighbors
|
||||
let dependents = pile.graph.neighbors(node).collect_vec();
|
||||
let edges = pile.graph.edges(node).map(|v| v.id()).collect_vec();
|
||||
for edge in edges {
|
||||
pile.graph.remove_edge(edge);
|
||||
}
|
||||
|
||||
// find how many nodes are reachable from z = 1 - these won't move
|
||||
let safe_blocks = fixed_nodes
|
||||
.iter()
|
||||
.flat_map(|origin| {
|
||||
Bfs::new(&pile.graph, *origin)
|
||||
.iter(&pile.graph)
|
||||
.map(|n| pile.graph[n].clone())
|
||||
})
|
||||
.unique()
|
||||
.count();
|
||||
// we are looking for the nodes that *will* disintegrate
|
||||
accum += pile.graph.node_count() - safe_blocks;
|
||||
// put the graph back how it was
|
||||
for neigh in dependents {
|
||||
pile.graph.add_edge(node, neigh, ());
|
||||
}
|
||||
}
|
||||
accum as u64
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "1,0,1~1,2,1
|
||||
0,0,2~2,0,2
|
||||
0,2,3~2,2,3
|
||||
0,0,4~0,2,4
|
||||
2,0,5~2,2,5
|
||||
0,1,6~2,1,6
|
||||
1,1,8~1,1,9";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(EXAMPLE), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(EXAMPLE), 7);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
use aoc_runner_derive::aoc;
|
||||
use itertools::Itertools;
|
||||
use ndarray::prelude::*;
|
||||
use petgraph::algo::all_simple_paths;
|
||||
use petgraph::prelude::*;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fmt::{Debug, Display, Write};
|
||||
|
||||
// PARSE
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Node {
|
||||
c: char,
|
||||
pos: Position,
|
||||
}
|
||||
|
||||
impl Display for Node {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "({},{})", self.pos.0, self.pos.1)
|
||||
}
|
||||
}
|
||||
|
||||
impl Debug for Node {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "({},{})", self.pos.0, self.pos.1)
|
||||
}
|
||||
}
|
||||
|
||||
type Position = (usize, usize);
|
||||
|
||||
#[derive(Clone)]
|
||||
struct ForestMap {
|
||||
map: Array2<char>,
|
||||
indexes: HashMap<Position, NodeIndex>,
|
||||
graph: StableDiGraph<Node, u64>,
|
||||
start: Position,
|
||||
end: Position,
|
||||
}
|
||||
|
||||
const ADJACENCIES: [(isize, isize); 4] = [(-1, 0), (1, 0), (0, -1), (0, 1)];
|
||||
|
||||
fn offset_pos(map: &Array2<char>, pos: Position, ofs: (isize, isize)) -> Option<Position> {
|
||||
let new_pos = (pos.0 as isize + ofs.0, pos.1 as isize + ofs.1);
|
||||
if new_pos.0 >= 0
|
||||
&& new_pos.0 < map.len_of(Axis(0)) as isize
|
||||
&& new_pos.1 >= 0
|
||||
&& new_pos.1 < map.len_of(Axis(1)) as isize
|
||||
{
|
||||
Some((new_pos.0 as usize, new_pos.1 as usize))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn adjacent_to(map: &Array2<char>, pos: Position) -> Vec<Position> {
|
||||
ADJACENCIES
|
||||
.iter()
|
||||
.filter_map(|ofs| offset_pos(map, pos, *ofs))
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl From<&str> for ForestMap {
|
||||
fn from(input: &str) -> Self {
|
||||
let rows = input.lines().map(|line| line.chars().collect_vec()).collect_vec();
|
||||
let map = Array::from_shape_vec([rows[0].len(), rows.len()], rows.into_iter().flatten().collect_vec())
|
||||
.unwrap()
|
||||
.reversed_axes();
|
||||
let start = (map.slice(s![.., 0]).iter().position(|c| *c == '.').unwrap(), 0);
|
||||
let end = (
|
||||
map.slice(s![.., map.len_of(Axis(1)) - 1])
|
||||
.iter()
|
||||
.position(|c| *c == '.')
|
||||
.unwrap(),
|
||||
map.len_of(Axis(1)) - 1,
|
||||
);
|
||||
|
||||
let mut graph = StableGraph::default();
|
||||
let mut indexes = HashMap::new();
|
||||
for (pos, c) in map.indexed_iter() {
|
||||
if *c != '#' {
|
||||
indexes.insert(pos, graph.add_node(Node { c: *c, pos }));
|
||||
}
|
||||
}
|
||||
|
||||
Self {
|
||||
map,
|
||||
start,
|
||||
end,
|
||||
graph,
|
||||
indexes,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ForestMap {
|
||||
fn build_graph(&mut self) {
|
||||
for (pos, c) in self.map.indexed_iter() {
|
||||
match c {
|
||||
'#' => continue,
|
||||
'.' => {
|
||||
adjacent_to(&self.map, pos).iter().for_each(|adj| {
|
||||
if self.indexes.contains_key(&adj) {
|
||||
self.graph.add_edge(self.indexes[&pos], self.indexes[adj], 1);
|
||||
}
|
||||
});
|
||||
}
|
||||
'^' => {
|
||||
if let Some(adj) = offset_pos(&self.map, pos, (0, -1)) {
|
||||
if self.indexes.contains_key(&adj) {
|
||||
self.graph.add_edge(self.indexes[&pos], self.indexes[&adj], 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
'>' => {
|
||||
if let Some(adj) = offset_pos(&self.map, pos, (1, 0)) {
|
||||
if self.indexes.contains_key(&adj) {
|
||||
self.graph.add_edge(self.indexes[&pos], self.indexes[&adj], 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
'v' => {
|
||||
if let Some(adj) = offset_pos(&self.map, pos, (0, 1)) {
|
||||
if self.indexes.contains_key(&adj) {
|
||||
self.graph.add_edge(self.indexes[&pos], self.indexes[&adj], 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
'<' => {
|
||||
if let Some(adj) = offset_pos(&self.map, pos, (-1, 0)) {
|
||||
if self.indexes.contains_key(&adj) {
|
||||
self.graph.add_edge(self.indexes[&pos], self.indexes[&adj], 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
c => panic!("invalid map character {}", c),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn build_graph2(&mut self) {
|
||||
for (pos, c) in self.map.indexed_iter() {
|
||||
match c {
|
||||
'#' => continue,
|
||||
'.' | '^' | '>' | 'v' | '<' => {
|
||||
adjacent_to(&self.map, pos).iter().for_each(|adj| {
|
||||
if self.indexes.contains_key(&adj) {
|
||||
self.graph.add_edge(self.indexes[&pos], self.indexes[adj], 1);
|
||||
}
|
||||
});
|
||||
}
|
||||
c => panic!("invalid map character {}", c),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Cull nodes that don't change the topology of the graph and combine their cost
|
||||
fn simplify_graph(&mut self) {
|
||||
let mut idxs: Vec<_> = self
|
||||
.graph
|
||||
.neighbors(self.indexes[&self.start])
|
||||
.map(|idx| (self.indexes[&self.start], idx))
|
||||
.collect();
|
||||
let mut visited = HashSet::from([self.indexes[&self.start]]);
|
||||
while let Some((last_idx, cur_idx)) = idxs.pop() {
|
||||
if !visited.insert(cur_idx) {
|
||||
continue;
|
||||
}
|
||||
let our_neighbors = self.graph.neighbors(cur_idx).collect_vec();
|
||||
|
||||
// if we have exactly 2 neighbours, then one is where we came from, and we can shortcut this node with a
|
||||
// pair of new edges A <-> C and break the existing 4 edges between them
|
||||
if our_neighbors.len() == 2 {
|
||||
let next_idx = our_neighbors.iter().find(|n| **n != last_idx).unwrap();
|
||||
|
||||
// remove the 4 existing edges
|
||||
// careful of order of operations, as removing edges invalidates edge indexes
|
||||
let forward_cost = self
|
||||
.graph
|
||||
.remove_edge(self.graph.find_edge(cur_idx, *next_idx).unwrap())
|
||||
.unwrap();
|
||||
let last_forward_cost = self
|
||||
.graph
|
||||
.remove_edge(self.graph.find_edge(last_idx, cur_idx).unwrap())
|
||||
.unwrap();
|
||||
let backward_cost = self
|
||||
.graph
|
||||
.remove_edge(self.graph.find_edge(cur_idx, last_idx).unwrap())
|
||||
.unwrap();
|
||||
let next_backward_cost = self
|
||||
.graph
|
||||
.remove_edge(self.graph.find_edge(*next_idx, cur_idx).unwrap())
|
||||
.unwrap();
|
||||
let new_forward_cost = forward_cost + last_forward_cost;
|
||||
let new_backward_cost = backward_cost + next_backward_cost;
|
||||
|
||||
// add edge from last to next
|
||||
self.graph.add_edge(last_idx, *next_idx, new_forward_cost);
|
||||
self.graph.add_edge(*next_idx, last_idx, new_backward_cost);
|
||||
|
||||
self.graph.remove_node(cur_idx);
|
||||
// push the next node
|
||||
idxs.push((last_idx, *next_idx));
|
||||
} else {
|
||||
// don't do anything about nodes with > 2 edges, just push them onto the stack, if there are some
|
||||
idxs.append(
|
||||
&mut self
|
||||
.graph
|
||||
.neighbors(cur_idx)
|
||||
.into_iter()
|
||||
.map(|next_idx| (cur_idx, next_idx))
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Debug for ForestMap {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
for y in 0..self.map.len_of(Axis(1)) {
|
||||
for c in self.map.index_axis(Axis(1), y) {
|
||||
f.write_char(*c)?;
|
||||
}
|
||||
writeln!(f)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// PROBLEM 1 solution
|
||||
|
||||
#[aoc(day23, part1)]
|
||||
fn part1(input: &str) -> u64 {
|
||||
let mut map = ForestMap::from(input);
|
||||
map.build_graph();
|
||||
// println!("{:?}", map);
|
||||
let paths = all_simple_paths::<Vec<_>, _>(&map.graph, map.indexes[&map.start], map.indexes[&map.end], 0, None)
|
||||
.collect_vec();
|
||||
let longest = paths.iter().max_by_key(|path| path.len()).unwrap();
|
||||
|
||||
longest.len() as u64 - 1
|
||||
}
|
||||
|
||||
fn calc_path_length(map: &ForestMap, path: &Vec<NodeIndex>) -> u64 {
|
||||
path.iter().tuple_windows().fold(0, |accum, (prev, next)| {
|
||||
accum + map.graph[map.graph.find_edge(*prev, *next).unwrap()]
|
||||
})
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
#[aoc(day23, part2)]
|
||||
fn part2(input: &str) -> u64 {
|
||||
let mut map = ForestMap::from(input);
|
||||
map.build_graph2();
|
||||
map.simplify_graph();
|
||||
|
||||
let paths = all_simple_paths::<Vec<_>, _>(&map.graph, map.indexes[&map.start], map.indexes[&map.end], 0, None)
|
||||
.collect_vec();
|
||||
let longest = paths.iter().max_by_key(|path| calc_path_length(&map, &path)).unwrap();
|
||||
longest.iter().tuple_windows().fold(0, |accum, (prev, next)| {
|
||||
accum + map.graph[map.graph.find_edge(*prev, *next).unwrap()]
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "#.#####################
|
||||
#.......#########...###
|
||||
#######.#########.#.###
|
||||
###.....#.>.>.###.#.###
|
||||
###v#####.#v#.###.#.###
|
||||
###.>...#.#.#.....#...#
|
||||
###v###.#.#.#########.#
|
||||
###...#.#.#.......#...#
|
||||
#####.#.#.#######.#.###
|
||||
#.....#.#.#.......#...#
|
||||
#.#####.#.#.#########v#
|
||||
#.#...#...#...###...>.#
|
||||
#.#.#v#######v###.###v#
|
||||
#...#.>.#...>.>.#.###.#
|
||||
#####v#.#.###v#.#.###.#
|
||||
#.....#...#...#.#.#...#
|
||||
#.#########.###.#.#.###
|
||||
#...###...#...#...#.###
|
||||
###.###.#.###v#####v###
|
||||
#...#...#.#.>.>.#.>.###
|
||||
#.###.###.#.###.#.#v###
|
||||
#.....###...###...#...#
|
||||
#####################.#";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(EXAMPLE), 94);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(EXAMPLE), 154);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
use aoc_runner_derive::aoc;
|
||||
use itertools::Itertools;
|
||||
use std::fmt::Debug;
|
||||
use std::ops::Index;
|
||||
|
||||
// Parse
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Vec3 {
|
||||
x: f64,
|
||||
y: f64,
|
||||
z: f64,
|
||||
}
|
||||
impl Debug for Vec3 {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}, {}, {}", self.x, self.y, self.z)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Vec2 {
|
||||
x: f64,
|
||||
y: f64,
|
||||
}
|
||||
impl Debug for Vec2 {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}, {}", self.x, self.y)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
|
||||
struct Hailstone {
|
||||
pos: Vec3,
|
||||
vel: Vec3,
|
||||
}
|
||||
|
||||
impl Hailstone {
|
||||
fn xy_vel_angle(&self) -> f64 {
|
||||
(self.vel.y / self.vel.x).atan()
|
||||
}
|
||||
fn xy_vel_abs(&self) -> f64 {
|
||||
(self.vel.x.powi(2) + self.vel.y.powi(2)).sqrt()
|
||||
}
|
||||
fn xy_slope(&self) -> f64 {
|
||||
self.vel.y / self.vel.x
|
||||
}
|
||||
fn y_crossing(&self) -> f64 {
|
||||
self.pos.y - self.xy_slope() * self.pos.x
|
||||
}
|
||||
fn xy_poi(&self, other: &Hailstone) -> Option<Vec2> {
|
||||
let our_slope = self.xy_slope();
|
||||
let other_slope = other.xy_slope();
|
||||
if our_slope == other_slope || our_slope * other_slope == -1. {
|
||||
None
|
||||
} else {
|
||||
let our_yint = self.y_crossing();
|
||||
let other_yint = other.y_crossing();
|
||||
let ratio = (other_yint - our_yint) / (our_slope - other_slope);
|
||||
Some(Vec2 {
|
||||
x: ratio,
|
||||
y: our_slope * ratio + our_yint,
|
||||
})
|
||||
}
|
||||
}
|
||||
fn xy_point_future(&self, point: &Vec2) -> bool {
|
||||
// a point will be in the past if the difference between its 'new' position and its 'start' position has a
|
||||
// different sign than the velocity for any component
|
||||
let diffs = [point.x - self.pos.x, point.y - self.pos.y];
|
||||
// for (diff, vel) in diffs.iter().zip([self.vel.x, self.vel.y].iter()) {
|
||||
// println!(" diff: {:?} vel: {:?} mul: {:?}", diff, vel, diff * vel > 0.);
|
||||
// }
|
||||
diffs
|
||||
.iter()
|
||||
.zip([self.vel.x, self.vel.y].iter())
|
||||
.any(|(diff, vel)| diff * vel > 0.)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for Hailstone {
|
||||
fn from(value: &str) -> Self {
|
||||
let (pos, vel) = value.split_once("@").unwrap();
|
||||
let [px, py, pz] = pos.split(",").map(|s| s.trim().parse::<f64>().unwrap()).collect_vec()[..] else {
|
||||
panic!()
|
||||
};
|
||||
let [vx, vy, vz] = vel.split(",").map(|s| s.trim().parse::<f64>().unwrap()).collect_vec()[..] else {
|
||||
panic!()
|
||||
};
|
||||
|
||||
Self {
|
||||
pos: Vec3 { x: px, y: py, z: pz },
|
||||
vel: Vec3 { x: vx, y: vy, z: vz },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Debug for Hailstone {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{:?} @ {:?}", self.pos, self.vel)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Hailstones {
|
||||
stones: Vec<Hailstone>,
|
||||
}
|
||||
|
||||
impl Hailstones {
|
||||
fn count_xy_pois(&self, bounds: (f64, f64)) -> u64 {
|
||||
assert!(bounds.0 < bounds.1);
|
||||
let mut stones = self.stones.clone();
|
||||
|
||||
let mut count = 0;
|
||||
while let Some(stone) = &stones.pop() {
|
||||
for other in &stones {
|
||||
let Some(poi) = stone.xy_poi(other) else { continue };
|
||||
// println!("intersection: {:?} / {:?} @ {:?}", stone, other, poi);
|
||||
if poi.x >= bounds.0
|
||||
&& poi.x <= bounds.1
|
||||
&& poi.y >= bounds.0
|
||||
&& poi.y <= bounds.1
|
||||
&& stone.xy_point_future(&poi)
|
||||
&& other.xy_point_future(&poi)
|
||||
{
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
count
|
||||
}
|
||||
}
|
||||
|
||||
impl Index<usize> for Hailstones {
|
||||
type Output = Hailstone;
|
||||
fn index(&self, index: usize) -> &Self::Output {
|
||||
&self.stones[index]
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for Hailstones {
|
||||
fn from(value: &str) -> Self {
|
||||
let mut stones = Vec::new();
|
||||
for line in value.lines() {
|
||||
stones.push(Hailstone::from(line));
|
||||
}
|
||||
Hailstones { stones }
|
||||
}
|
||||
}
|
||||
|
||||
// PROBLEM 1 solution
|
||||
|
||||
#[aoc(day24, part1)]
|
||||
fn part1(input: &str) -> u64 {
|
||||
problem1_impl(input, (200000000000000., 400000000000000.))
|
||||
}
|
||||
|
||||
fn problem1_impl(input: &str, bounds: (f64, f64)) -> u64 {
|
||||
let stones = Hailstones::from(input);
|
||||
|
||||
stones.count_xy_pois(bounds)
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
#[aoc(day24, part2)]
|
||||
fn part2(input: &str) -> u64 {
|
||||
0
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "19, 13, 30 @ -2, 1, -2
|
||||
18, 19, 22 @ -1, -1, -2
|
||||
20, 25, 34 @ -2, -2, -4
|
||||
12, 31, 28 @ -1, -2, -1
|
||||
20, 19, 15 @ 1, -5, -3";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(problem1_impl(EXAMPLE, (7., 27.)), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(EXAMPLE), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
use aoc_runner_derive::aoc;
|
||||
use indicatif::{ProgressBar, ProgressIterator, ProgressStyle};
|
||||
use itertools::Itertools;
|
||||
use petgraph::algo::connected_components;
|
||||
#[allow(unused)]
|
||||
use petgraph::dot::Dot;
|
||||
use petgraph::prelude::*;
|
||||
use petgraph::visit::{depth_first_search, DfsEvent, IntoEdgeReferences, IntoNodeIdentifiers, IntoNodeReferences};
|
||||
use rayon::prelude::*;
|
||||
use std::collections::HashMap;
|
||||
|
||||
// PARSE
|
||||
|
||||
struct Circuit {
|
||||
graph: UnGraph<String, String>,
|
||||
nodes: HashMap<String, Node>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Node {
|
||||
targets: Vec<String>,
|
||||
index: Option<NodeIndex>,
|
||||
}
|
||||
|
||||
impl Node {
|
||||
fn with_index(mut self, index: NodeIndex) -> Self {
|
||||
self.index = Some(index);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for Circuit {
|
||||
fn from(input: &str) -> Self {
|
||||
let mut graph = UnGraph::default();
|
||||
let mut nodes = HashMap::new();
|
||||
for line in input.lines() {
|
||||
let (source, targets_s) = line.split_once(": ").unwrap();
|
||||
let targets = targets_s.split_whitespace().map(|s| s.to_string()).collect_vec();
|
||||
nodes.insert(
|
||||
source.to_string(),
|
||||
Node {
|
||||
targets,
|
||||
index: Some(graph.add_node(source.to_string())),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
for (name, node) in nodes.iter_mut() {
|
||||
for target in &node.targets {
|
||||
let target_idx = match graph.node_references().find(|n| n.1 == target).map(|n| n.0) {
|
||||
Some(target) => target,
|
||||
None => graph.add_node(target.to_string()),
|
||||
};
|
||||
graph.add_edge(node.index.unwrap(), target_idx, format!("{}-{}", name, target));
|
||||
}
|
||||
}
|
||||
|
||||
Self { graph, nodes }
|
||||
}
|
||||
}
|
||||
|
||||
impl Circuit {
|
||||
// returns the set of nodes on each side
|
||||
fn find_critical_edges(&self, removals: usize) -> (Vec<String>, Vec<String>) {
|
||||
let bar = ProgressBar::new(self.graph.edge_references().combinations(removals).try_len().unwrap() as u64)
|
||||
.with_style(
|
||||
ProgressStyle::with_template(
|
||||
"[{elapsed_precise}/{eta_precise}] {bar:40.cyan/blue} {pos:>7}/{len:7} {per_sec}",
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
// for set in self.graph.edge_references().combinations(removals).progress_with(bar) {
|
||||
|
||||
let set = [("zcp", "zjm"), ("rsg", "nsk"), ("jks", "rfg")]
|
||||
.iter()
|
||||
.flat_map(|(src, dst)| {
|
||||
self.graph.edge_references().filter(|e| {
|
||||
self.graph[e.source()] == *src && self.graph[e.target()] == *dst
|
||||
|| self.graph[e.target()] == *src && self.graph[e.source()] == *dst
|
||||
})
|
||||
})
|
||||
.collect_vec();
|
||||
let mut local_graph: StableUnGraph<_, _> = self.graph.clone().into();
|
||||
for wire in &set {
|
||||
local_graph.remove_edge(wire.id());
|
||||
}
|
||||
let local_graph = UnGraph::from(local_graph);
|
||||
if connected_components(&local_graph) == 2 {
|
||||
// each edge will have one leg in each component, so return the set of connected nodes
|
||||
let mut left = Vec::new();
|
||||
depth_first_search(&local_graph, Some(set[0].source()), |event| {
|
||||
if let DfsEvent::Discover(n, t) = event {
|
||||
left.push(local_graph[n].to_string());
|
||||
}
|
||||
});
|
||||
let mut right = Vec::new();
|
||||
depth_first_search(&local_graph, Some(set[0].target()), |event| {
|
||||
if let DfsEvent::Discover(n, t) = event {
|
||||
right.push(local_graph[n].to_string());
|
||||
}
|
||||
});
|
||||
return (left, right);
|
||||
}
|
||||
// }
|
||||
panic!("no cutline found");
|
||||
}
|
||||
}
|
||||
|
||||
// PROBLEM 1 solution
|
||||
|
||||
#[aoc(day25, part1)]
|
||||
fn part1(input: &str) -> u64 {
|
||||
let circuit = Circuit::from(input);
|
||||
// println!("{:?}", Dot::new(&circuit.graph));
|
||||
let (left, right) = circuit.find_critical_edges(3);
|
||||
(left.len() * right.len()) as u64
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
#[aoc(day25, part2)]
|
||||
fn part2(input: &str) -> u64 {
|
||||
0
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "jqt: rhn xhk nvd
|
||||
rsh: frs pzl lsr
|
||||
xhk: hfx
|
||||
cmg: qnr nvd lhk bvb
|
||||
rhn: xhk bvb hfx
|
||||
bvb: xhk hfx
|
||||
pzl: lsr hfx nvd
|
||||
qnr: nvd
|
||||
ntq: jqt hfx bvb xhk
|
||||
nvd: lhk
|
||||
lsr: lhk
|
||||
rzs: qnr cmg lsr rsh
|
||||
frs: qnr lhk lsr";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(EXAMPLE), 54);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(EXAMPLE), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use num::traits;
|
||||
use std::ops::Range;
|
||||
|
||||
// --- Day 3: Gear Ratios ---
|
||||
|
||||
// You and the Elf eventually reach a gondola lift station; he says the gondola lift
|
||||
// will take you up to the water source, but this is as far as he can bring you. You go
|
||||
// inside.
|
||||
|
||||
// It doesn't take long to find the gondolas, but there seems to be a problem: they're
|
||||
// not moving.
|
||||
|
||||
// "Aaah!"
|
||||
|
||||
// You turn around to see a slightly-greasy Elf with a wrench and a look of surprise.
|
||||
// "Sorry, I wasn't expecting anyone! The gondola lift isn't working right now; it'll
|
||||
// still be a while before I can fix it." You offer to help.
|
||||
|
||||
// The engineer explains that an engine part seems to be missing from the engine, but
|
||||
// nobody can figure out which one. If you can add up all the part numbers in the engine
|
||||
// schematic, it should be easy to work out which part is missing.
|
||||
|
||||
// The engine schematic (your puzzle input) consists of a visual representation of the
|
||||
// engine. There are lots of numbers and symbols you don't really understand, but
|
||||
// apparently any number adjacent to a symbol, even diagonally, is a "part number" and
|
||||
// should be included in your sum. (Periods (.) do not count as a symbol.)
|
||||
|
||||
// Here is an example engine schematic:
|
||||
|
||||
// 467..114.. ...*...... ..35..633. ......#... 617*...... .....+.58. ..592.....
|
||||
// ......755. ...$.*.... .664.598..
|
||||
|
||||
// In this schematic, two numbers are not part numbers because they are not adjacent to
|
||||
// a symbol: 114 (top right) and 58 (middle right). Every other number is adjacent to a
|
||||
// symbol and so is a part number; their sum is 4361.
|
||||
|
||||
// PARSING
|
||||
|
||||
// We will store the schematic as a 2D Vector of char
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Pos(usize, usize);
|
||||
|
||||
// Outer Vec holds rows, so addressing is column then row
|
||||
#[derive(Debug)]
|
||||
struct SchematicRow(Vec<char>);
|
||||
#[derive(Debug)]
|
||||
struct Schematic(Vec<SchematicRow>);
|
||||
|
||||
impl From<&str> for SchematicRow {
|
||||
fn from(s: &str) -> Self {
|
||||
SchematicRow(s.chars().collect())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for Schematic {
|
||||
fn from(input: &str) -> Self {
|
||||
Self(input.lines().map(|line| line.into()).collect())
|
||||
}
|
||||
}
|
||||
|
||||
const ADJACENCY_OFFSETS: &[(i64, i64)] = &[(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)];
|
||||
|
||||
// We assume the schematic is composed of equal length lines
|
||||
impl Schematic {
|
||||
fn in_bounds<T: PartialOrd + num::traits::Zero + TryFrom<usize>>(&self, x: T, y: T) -> bool {
|
||||
let x_bound: T = self.0[0].0.len().try_into().unwrap_or_else(|_| panic!("bad bounds"));
|
||||
let y_bound: T = self.0.len().try_into().unwrap_or_else(|_| panic!("bad bounds"));
|
||||
x >= T::zero() && x < x_bound && y >= T::zero() && y < y_bound
|
||||
}
|
||||
fn at(&self, pos: &Pos) -> char {
|
||||
self.0[pos.1].0[pos.0]
|
||||
}
|
||||
|
||||
fn adjacent_to_symbol(&self, pos: &Pos) -> bool {
|
||||
ADJACENCY_OFFSETS.iter().any(|(x_ofs, y_ofs)| {
|
||||
let adj_x = (pos.0 as i64) + x_ofs;
|
||||
let adj_y = (pos.1 as i64) + y_ofs;
|
||||
|
||||
if !self.in_bounds(adj_x, adj_y) {
|
||||
false
|
||||
} else {
|
||||
let adj_c = self.at(&Pos(adj_x as usize, adj_y as usize));
|
||||
adj_c != '.' && adj_c.is_ascii_punctuation()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn is_gear(&self, pos: &Pos) -> bool {
|
||||
if self.at(pos) != '*' {
|
||||
return false;
|
||||
}
|
||||
|
||||
ADJACENCY_OFFSETS
|
||||
.iter()
|
||||
.filter(|(x_ofs, y_ofs)| {
|
||||
let adj_x = (pos.0 as i64) + x_ofs;
|
||||
let adj_y = (pos.1 as i64) + y_ofs;
|
||||
|
||||
if adj_x < 0 || adj_x >= self.0[pos.1].0.len() as i64 || adj_y < 0 || adj_y >= self.0.len() as i64 {
|
||||
false
|
||||
} else {
|
||||
let adj_c = self.at(&Pos(adj_x as usize, adj_y as usize));
|
||||
adj_c.is_digit(10)
|
||||
}
|
||||
})
|
||||
.count()
|
||||
>= 2
|
||||
}
|
||||
|
||||
fn gear_ratio(&self, pos: &Pos) -> Option<u64> {
|
||||
if self.at(pos) != '*' {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut exclusions: Vec<(Range<usize>, i64)> = Vec::new();
|
||||
let mut nums = (0u64, 0u64);
|
||||
|
||||
for (x_ofs, y_ofs) in ADJACENCY_OFFSETS {
|
||||
let adj_x = (pos.0 as i64) + x_ofs;
|
||||
let adj_y = (pos.1 as i64) + y_ofs;
|
||||
if !self.in_bounds(adj_x, adj_y)
|
||||
|| exclusions
|
||||
.iter()
|
||||
.any(|(ex_x_range, ex_y)| *ex_y == adj_y && ex_x_range.contains(&(adj_x as usize)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let adj_c = self.at(&Pos(adj_x as usize, adj_y as usize));
|
||||
if adj_c.is_digit(10) {
|
||||
let mut num_start_x = adj_x as usize;
|
||||
loop {
|
||||
if num_start_x > 0 && self.at(&Pos((num_start_x - 1) as usize, adj_y as usize)).is_digit(10) {
|
||||
num_start_x -= 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let mut num_end_x = adj_x as usize;
|
||||
loop {
|
||||
if self.in_bounds(num_end_x + 1, adj_y as usize)
|
||||
&& self.at(&Pos((num_end_x + 1) as usize, adj_y as usize)).is_digit(10)
|
||||
{
|
||||
num_end_x += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// we have the bounds for the number, extract a slice
|
||||
let num_slice = &self.0[adj_y as usize].0[num_start_x..num_end_x + 1];
|
||||
let mut num = 0u64;
|
||||
for c in num_slice {
|
||||
num = num * 10 + c.to_digit(10).unwrap() as u64;
|
||||
}
|
||||
if nums.0 == 0 {
|
||||
nums.0 = num
|
||||
} else {
|
||||
nums.1 = num;
|
||||
return Some(nums.0 * nums.1);
|
||||
}
|
||||
exclusions.push((num_start_x..num_end_x + 1, adj_y));
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
// PROBLEM 1 solution
|
||||
|
||||
// Of course, the actual engine schematic is much larger. What is the sum of all of the
|
||||
// part numbers in the engine schematic?
|
||||
|
||||
fn problem1_all_valid_part_numbers(schematic: &Schematic) -> Vec<u64> {
|
||||
let mut results = Vec::new();
|
||||
|
||||
let mut cur_pos = Pos(0usize, 0usize);
|
||||
|
||||
while cur_pos.1 < schematic.0.len() {
|
||||
while cur_pos.0 < schematic.0[0].0.len() {
|
||||
let c = schematic.at(&cur_pos);
|
||||
if c.is_digit(10) {
|
||||
let mut valid: bool = schematic.adjacent_to_symbol(&cur_pos);
|
||||
let mut num = c.to_digit(10).unwrap() as u64;
|
||||
loop {
|
||||
if cur_pos.0 + 1 >= schematic.0[0].0.len() {
|
||||
break;
|
||||
}
|
||||
cur_pos.0 += 1;
|
||||
if schematic.at(&cur_pos).is_digit(10) {
|
||||
num = num * 10 + schematic.at(&cur_pos).to_digit(10).unwrap() as u64;
|
||||
valid = valid || schematic.adjacent_to_symbol(&cur_pos);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if valid {
|
||||
results.push(num);
|
||||
}
|
||||
}
|
||||
cur_pos.0 += 1;
|
||||
}
|
||||
cur_pos.1 += 1;
|
||||
cur_pos.0 = 0;
|
||||
}
|
||||
|
||||
results
|
||||
}
|
||||
|
||||
#[aoc_generator(day3)]
|
||||
fn parse(input: &str) -> Schematic {
|
||||
input.into()
|
||||
}
|
||||
|
||||
#[aoc(day3, part1)]
|
||||
fn part1(schematic: &Schematic) -> u64 {
|
||||
problem1_all_valid_part_numbers(schematic).iter().sum()
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
|
||||
// --- Part Two ---
|
||||
|
||||
// The engineer finds the missing part and installs it in the engine! As the engine
|
||||
// springs to life, you jump in the closest gondola, finally ready to ascend to the
|
||||
// water source.
|
||||
|
||||
// You don't seem to be going very fast, though. Maybe something is still wrong?
|
||||
// Fortunately, the gondola has a phone labeled "help", so you pick it up and the
|
||||
// engineer answers.
|
||||
|
||||
// Before you can explain the situation, she suggests that you look out the window.
|
||||
// There stands the engineer, holding a phone in one hand and waving with the other.
|
||||
// You're going so slowly that you haven't even left the station. You exit the gondola.
|
||||
|
||||
// The missing part wasn't the only issue - one of the gears in the engine is wrong. A
|
||||
// gear is any * symbol that is adjacent to exactly two part numbers. Its gear ratio is
|
||||
// the result of multiplying those two numbers together.
|
||||
|
||||
// This time, you need to find the gear ratio of every gear and add them all up so that
|
||||
// the engineer can figure out which gear needs to be replaced.
|
||||
|
||||
// Consider the same engine schematic again:
|
||||
|
||||
// 467..114.. ...*...... ..35..633. ......#... 617*...... .....+.58. ..592.....
|
||||
// ......755. ...$.*.... .664.598..
|
||||
|
||||
// In this schematic, there are two gears. The first is in the top left; it has part
|
||||
// numbers 467 and 35, so its gear ratio is 16345. The second gear is in the lower
|
||||
// right; its gear ratio is 451490. (The * adjacent to 617 is not a gear because it is
|
||||
// only adjacent to one part number.) Adding up all of the gear ratios produces 467835.
|
||||
|
||||
// What is the sum of all of the gear ratios in your engine schematic?
|
||||
|
||||
fn problem2_all_gear_ratios(schematic: &Schematic) -> Vec<u64> {
|
||||
let mut gears = Vec::new();
|
||||
for y in 0..schematic.0.len() {
|
||||
for x in 0..schematic.0[0].0.len() {
|
||||
match schematic.gear_ratio(&Pos(x, y)) {
|
||||
Some(ratio) => gears.push(ratio),
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
gears
|
||||
}
|
||||
|
||||
#[aoc(day3, part2)]
|
||||
fn part2(schematic: &Schematic) -> u64 {
|
||||
problem2_all_gear_ratios(schematic).iter().sum()
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use lazy_regex::{lazy_regex, Lazy, Regex};
|
||||
|
||||
// --- Day 4: Scratchcards ---
|
||||
|
||||
// The gondola takes you up. Strangely, though, the ground doesn't seem to be coming
|
||||
// with you; you're not climbing a mountain. As the circle of Snow Island recedes below
|
||||
// you, an entire new landmass suddenly appears above you! The gondola carries you to
|
||||
// the surface of the new island and lurches into the station.
|
||||
|
||||
// As you exit the gondola, the first thing you notice is that the air here is much
|
||||
// warmer than it was on Snow Island. It's also quite humid. Is this where the water
|
||||
// source is?
|
||||
|
||||
// The next thing you notice is an Elf sitting on the floor across the station in what
|
||||
// seems to be a pile of colorful square cards.
|
||||
|
||||
// "Oh! Hello!" The Elf excitedly runs over to you. "How may I be of service?" You ask
|
||||
// about water sources.
|
||||
|
||||
// "I'm not sure; I just operate the gondola lift. That does sound like something we'd
|
||||
// have, though - this is Island Island, after all! I bet the gardener would know. He's
|
||||
// on a different island, though - er, the small kind surrounded by water, not the
|
||||
// floating kind. We really need to come up with a better naming scheme. Tell you what:
|
||||
// if you can help me with something quick, I'll let you borrow my boat and you can go
|
||||
// visit the gardener. I got all these scratchcards as a gift, but I can't figure out
|
||||
// what I've won."
|
||||
|
||||
// The Elf leads you over to the pile of colorful cards. There, you discover dozens of
|
||||
// scratchcards, all with their opaque covering already scratched off. Picking one up,
|
||||
// it looks like each card has two lists of numbers separated by a vertical bar (|): a
|
||||
// list of winning numbers and then a list of numbers you have. You organize the
|
||||
// information into a table (your puzzle input).
|
||||
|
||||
// PARSING
|
||||
|
||||
const CARD_REGEX: Lazy<Regex> = lazy_regex!(r"^Card\s+([0-9]+):(.+)\|(.+)$");
|
||||
|
||||
fn num_list(s: &str) -> Vec<u32> {
|
||||
s.split_whitespace().map(|s_num| s_num.parse().unwrap()).collect()
|
||||
}
|
||||
|
||||
pub struct Card {
|
||||
id: usize,
|
||||
winning_numbers: Vec<u32>,
|
||||
our_numbers: Vec<u32>,
|
||||
}
|
||||
|
||||
impl Card {
|
||||
fn score(&self) -> u64 {
|
||||
let match_count = self
|
||||
.winning_numbers
|
||||
.iter()
|
||||
.filter(|win| self.our_numbers.contains(win))
|
||||
.count();
|
||||
if match_count > 0 {
|
||||
1 << (match_count - 1)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
// Return the number of copies won
|
||||
fn win_copies(&self) -> usize {
|
||||
self.winning_numbers
|
||||
.iter()
|
||||
.filter(|win| self.our_numbers.contains(win))
|
||||
.count()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for Card {
|
||||
fn from(s: &str) -> Self {
|
||||
let parts = CARD_REGEX.captures(s).unwrap();
|
||||
Card {
|
||||
id: parts.get(1).unwrap().as_str().parse().unwrap(),
|
||||
winning_numbers: num_list(parts.get(2).unwrap().as_str()),
|
||||
our_numbers: num_list(parts.get(3).unwrap().as_str()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// PROBLEM 1 solution
|
||||
|
||||
// As far as the Elf has been able to figure out, you have to figure out which of the
|
||||
// numbers you have appear in the list of winning numbers. The first match makes the
|
||||
// card worth one point and each match after the first doubles the point value of that
|
||||
// card.
|
||||
|
||||
// For example:
|
||||
|
||||
// Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53
|
||||
// Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19
|
||||
// Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1
|
||||
// Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83
|
||||
// Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36
|
||||
// Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11
|
||||
|
||||
// In the above example, card 1 has five winning numbers (41, 48, 83, 86, and 17) and
|
||||
// eight numbers you have (83, 86, 6, 31, 17, 9, 48, and 53). Of the numbers you have,
|
||||
// four of them (48, 83, 17, and 86) are winning numbers! That means card 1 is worth 8
|
||||
// points (1 for the first match, then doubled three times for each of the three matches
|
||||
// after the first).
|
||||
|
||||
// Card 2 has two winning numbers (32 and 61), so it is worth 2 points. Card 3 has
|
||||
// two winning numbers (1 and 21), so it is worth 2 points. Card 4 has one winning
|
||||
// number (84), so it is worth 1 point. Card 5 has no winning numbers, so it is
|
||||
// worth no points. Card 6 has no winning numbers, so it is worth no points.
|
||||
|
||||
// So, in this example, the Elf's pile of scratchcards is worth 13 points.
|
||||
|
||||
// Take a seat in the large pile of colorful cards. How many points are they worth in
|
||||
// total?
|
||||
|
||||
#[aoc_generator(day4)]
|
||||
fn parse(input: &str) -> Vec<Card> {
|
||||
input.lines().map(|line| Card::from(line)).collect()
|
||||
}
|
||||
|
||||
#[aoc(day4, part1)]
|
||||
fn part1(cards: &[Card]) -> u64 {
|
||||
cards.iter().map(|x| x.score()).sum()
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
|
||||
// --- Part Two ---
|
||||
|
||||
// Just as you're about to report your findings to the Elf, one of you realizes that the
|
||||
// rules have actually been printed on the back of every card this whole time.
|
||||
|
||||
// There's no such thing as "points". Instead, scratchcards only cause you to win more
|
||||
// scratchcards equal to the number of winning numbers you have.
|
||||
|
||||
// Specifically, you win copies of the scratchcards below the winning card equal to the
|
||||
// number of matches. So, if card 10 were to have 5 matching numbers, you would win one
|
||||
// copy each of cards 11, 12, 13, 14, and 15.
|
||||
|
||||
// Copies of scratchcards are scored like normal scratchcards and have the same card
|
||||
// number as the card they copied. So, if you win a copy of card 10 and it has 5
|
||||
// matching numbers, it would then win a copy of the same cards that the original card
|
||||
// 10 won: cards 11, 12, 13, 14, and 15. This process repeats until none of the copies
|
||||
// cause you to win any more cards. (Cards will never make you copy a card past the end
|
||||
// of the table.)
|
||||
|
||||
// This time, the above example goes differently:
|
||||
|
||||
// Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53 Card 2: 13 32 20 16 61 | 61 30 68 82
|
||||
// 17 32 24 19 Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1 Card 4: 41 92 73 84 69 |
|
||||
// 59 84 76 51 58 5 54 83 Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36 Card 6: 31
|
||||
// 18 13 56 72 | 74 77 10 23 35 67 36 11
|
||||
|
||||
// Card 1 has four matching numbers, so you win one copy each of the next four
|
||||
// cards: cards 2, 3, 4, and 5. Your original card 2 has two matching numbers, so
|
||||
// you win one copy each of cards 3 and 4. Your copy of card 2 also wins one copy
|
||||
// each of cards 3 and 4. Your four instances of card 3 (one original and three
|
||||
// copies) have two matching numbers, so you win four copies each of cards 4 and 5.
|
||||
// Your eight instances of card 4 (one original and seven copies) have one matching
|
||||
// number, so you win eight copies of card 5. Your fourteen instances of card 5 (one
|
||||
// original and thirteen copies) have no matching numbers and win no more cards.
|
||||
// Your one instance of card 6 (one original) has no matching numbers and wins no
|
||||
// more cards.
|
||||
|
||||
// Once all of the originals and copies have been processed, you end up with 1 instance
|
||||
// of card 1, 2 instances of card 2, 4 instances of card 3, 8 instances of card 4, 14
|
||||
// instances of card 5, and 1 instance of card 6. In total, this example pile of
|
||||
// scratchcards causes you to ultimately have 30 scratchcards!
|
||||
|
||||
// Process all of the original and copied scratchcards until no more scratchcards are
|
||||
// won. Including the original set of scratchcards, how many total scratchcards do you
|
||||
// end up with?
|
||||
|
||||
fn problem2_award_copies<'a>(orig_cards: &'a [Card], card: &Card) -> Vec<&'a Card> {
|
||||
let win_copies = card.win_copies();
|
||||
let mut new_cards = Vec::new();
|
||||
if win_copies != 0 {
|
||||
for ofs in 0..win_copies {
|
||||
// card.id is 1-indexed, so would need to be card.id-1, but offset needs to
|
||||
// start at 1, which offsets this
|
||||
new_cards.push(&orig_cards[card.id + ofs]);
|
||||
}
|
||||
}
|
||||
|
||||
new_cards
|
||||
}
|
||||
|
||||
#[aoc(day4, part2)]
|
||||
fn part2(orig_cards: &[Card]) -> u64 {
|
||||
let mut new_cards = Vec::new();
|
||||
let mut won_cards = Vec::new();
|
||||
|
||||
for card in orig_cards {
|
||||
new_cards.append(&mut problem2_award_copies(orig_cards, card))
|
||||
}
|
||||
|
||||
while let Some(card) = new_cards.pop() {
|
||||
won_cards.push(card);
|
||||
new_cards.append(&mut problem2_award_copies(orig_cards, card))
|
||||
}
|
||||
|
||||
(won_cards.len() + orig_cards.len()) as u64
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const example_input: &str = "Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53
|
||||
Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19
|
||||
Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1
|
||||
Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83
|
||||
Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36
|
||||
Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(&parse(example_input)), 13);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(&parse(example_input)), 30);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,479 @@
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use std::ops::Range;
|
||||
use std::str::Lines;
|
||||
|
||||
use itertools::Itertools;
|
||||
|
||||
// --- Day 5: If You Give A Seed A Fertilizer ---
|
||||
|
||||
// You take the boat and find the gardener right where you were told he would be:
|
||||
// managing a giant "garden" that looks more to you like a farm.
|
||||
|
||||
// "A water source? Island Island is the water source!" You point out that Snow Island
|
||||
// isn't receiving any water.
|
||||
|
||||
// "Oh, we had to stop the water because we ran out of sand to filter it with! Can't
|
||||
// make snow with dirty water. Don't worry, I'm sure we'll get more sand soon; we only
|
||||
// turned off the water a few days... weeks... oh no." His face sinks into a look of
|
||||
// horrified realization.
|
||||
|
||||
// "I've been so busy making sure everyone here has food that I completely forgot to
|
||||
// check why we stopped getting more sand! There's a ferry leaving soon that is headed
|
||||
// over in that direction - it's much faster than your boat. Could you please go check
|
||||
// it out?"
|
||||
|
||||
// You barely have time to agree to this request when he brings up another. "While you
|
||||
// wait for the ferry, maybe you can help us with our food production problem. The
|
||||
// latest Island Island Almanac just arrived and we're having trouble making sense of
|
||||
// it."
|
||||
|
||||
// The almanac (your puzzle input) lists all of the seeds that need to be planted. It
|
||||
// also lists what type of soil to use with each kind of seed, what type of fertilizer
|
||||
// to use with each kind of soil, what type of water to use with each kind of
|
||||
// fertilizer, and so on. Every type of seed, soil, fertilizer and so on is identified
|
||||
// with a number, but numbers are reused by each category - that is, soil 123 and
|
||||
// fertilizer 123 aren't necessarily related to each other.
|
||||
|
||||
// For example:
|
||||
|
||||
// seeds: 79 14 55 13
|
||||
//
|
||||
// seed-to-soil map:
|
||||
// 50 98 2
|
||||
// 52 50 48
|
||||
//
|
||||
// soil-to-fertilizer map:
|
||||
// 0 15 37
|
||||
// 37 52 2
|
||||
// 39 0 15
|
||||
//
|
||||
// fertilizer-to-water map:
|
||||
// 49 53 8
|
||||
// 0 11 42
|
||||
// 42 0 7
|
||||
// 57 7 4
|
||||
//
|
||||
// water-to-light map:
|
||||
// 88 18 7
|
||||
// 18 25 70
|
||||
//
|
||||
// light-to-temperature map:
|
||||
// 45 77 23
|
||||
// 81 45 19
|
||||
// 68 64 13
|
||||
//
|
||||
// temperature-to-humidity map:
|
||||
// 0 69 1
|
||||
// 1 0 69
|
||||
//
|
||||
// humidity-to-location map:
|
||||
// 60 56 37
|
||||
// 56 93 4
|
||||
|
||||
// The almanac starts by listing which seeds need to be planted: seeds 79, 14, 55, and 13.
|
||||
|
||||
// The rest of the almanac contains a list of maps which describe how to convert numbers
|
||||
// from a source category into numbers in a destination category. That is, the section
|
||||
// that starts with seed-to-soil map: describes how to convert a seed number (the
|
||||
// source) to a soil number (the destination). This lets the gardener and his team know
|
||||
// which soil to use with which seeds, which water to use with which fertilizer, and so
|
||||
// on.
|
||||
|
||||
// Rather than list every source number and its corresponding destination number one by
|
||||
// one, the maps describe entire ranges of numbers that can be converted. Each line
|
||||
// within a map contains three numbers: the destination range start, the source range
|
||||
// start, and the range length.
|
||||
|
||||
// Consider again the example seed-to-soil map:
|
||||
|
||||
// 50 98 2
|
||||
// 52 50 48
|
||||
|
||||
// The first line has a destination range start of 50, a source range start of 98, and a
|
||||
// range length of 2. This line means that the source range starts at 98 and contains
|
||||
// two values: 98 and 99. The destination range is the same length, but it starts at 50,
|
||||
// so its two values are 50 and 51. With this information, you know that seed number 98
|
||||
// corresponds to soil number 50 and that seed number 99 corresponds to soil number 51.
|
||||
|
||||
// The second line means that the source range starts at 50 and contains 48 values: 50,
|
||||
// 51, ..., 96, 97. This corresponds to a destination range starting at 52 and also
|
||||
// containing 48 values: 52, 53, ..., 98, 99. So, seed number 53 corresponds to soil
|
||||
// number 55.
|
||||
|
||||
// Any source numbers that aren't mapped correspond to the same destination number. So,
|
||||
// seed number 10 corresponds to soil number 10.
|
||||
|
||||
// So, the entire list of seed numbers and their corresponding soil numbers looks like
|
||||
// this:
|
||||
|
||||
// seed soil
|
||||
// 0 0
|
||||
// 1 1
|
||||
// ... ...
|
||||
// 48 48
|
||||
// 49 49
|
||||
// 50 52
|
||||
// 51 53
|
||||
// ... ...
|
||||
// 96 98
|
||||
// 97 99
|
||||
// 98 50
|
||||
// 99 51
|
||||
|
||||
// With this map, you can look up the soil number required for each initial seed number:
|
||||
|
||||
// Seed number 79 corresponds to soil number 81.
|
||||
// Seed number 14 corresponds to soil number 14.
|
||||
// Seed number 55 corresponds to soil number 57.
|
||||
// Seed number 13 corresponds to soil number 13.
|
||||
|
||||
// PARSING
|
||||
|
||||
#[derive(Debug)]
|
||||
struct AlmanacMapping {
|
||||
source_range: Range<i64>,
|
||||
dest_range: Range<i64>,
|
||||
}
|
||||
|
||||
impl From<&str> for AlmanacMapping {
|
||||
fn from(s: &str) -> Self {
|
||||
let s_nums: Vec<_> = s.split_whitespace().take(3).collect();
|
||||
let length: i64 = s_nums[2].parse().unwrap();
|
||||
let source_start: i64 = s_nums[1].parse().unwrap();
|
||||
let dest_start: i64 = s_nums[0].parse().unwrap();
|
||||
AlmanacMapping {
|
||||
source_range: source_start..source_start + length,
|
||||
dest_range: dest_start..dest_start + length,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AlmanacMapping {
|
||||
fn lookup(&self, key: i64) -> Option<i64> {
|
||||
if self.source_range.contains(&key) {
|
||||
Some(self.dest_range.start + (key - self.source_range.start))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct AlmanacMappingTable {
|
||||
name: String,
|
||||
mappings: Vec<AlmanacMapping>,
|
||||
}
|
||||
|
||||
fn range_overlap<T: num::Num + Ord + Copy>(r1: &Range<T>, r2: &Range<T>) -> Option<Range<T>> {
|
||||
let new_start = std::cmp::max(r1.start, r2.start);
|
||||
let new_end = std::cmp::min(r1.end - T::one(), r2.end - T::one());
|
||||
|
||||
if new_start <= std::cmp::min(r1.end - T::one(), r2.end - T::one()) && new_end >= std::cmp::max(r1.start, r2.start)
|
||||
{
|
||||
Some(new_start..new_end + T::one())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn range_exclude<T: num::Num + Ord + Copy>(keep: &Range<T>, exclude: &Range<T>) -> Vec<Range<T>> {
|
||||
let mut residual = Vec::new();
|
||||
if let Some(overlap) = range_overlap(keep, exclude) {
|
||||
if keep.start < overlap.start {
|
||||
residual.push(keep.start..overlap.start);
|
||||
}
|
||||
if keep.end > overlap.end {
|
||||
residual.push(overlap.end..keep.end);
|
||||
}
|
||||
} else {
|
||||
residual.push(keep.clone());
|
||||
}
|
||||
residual
|
||||
}
|
||||
|
||||
impl AlmanacMappingTable {
|
||||
fn lookup(&self, key: i64) -> i64 {
|
||||
self.mappings.iter().find_map(|map| map.lookup(key)).unwrap_or(key)
|
||||
}
|
||||
fn lookup_ranges(&self, ranges: Vec<Range<i64>>) -> Vec<Range<i64>> {
|
||||
ranges.iter().flat_map(|range| self.lookup_range(range)).collect()
|
||||
}
|
||||
fn lookup_range(&self, range: &Range<i64>) -> Vec<Range<i64>> {
|
||||
let mut residual = vec![range.clone()];
|
||||
let mut resolved_mappings = Vec::new();
|
||||
|
||||
for map in &self.mappings {
|
||||
let mut local_residual = Vec::new();
|
||||
for range in residual.into_iter() {
|
||||
if let Some(overlap) = range_overlap(&range, &map.source_range) {
|
||||
let dest_start_idx = overlap.start - map.source_range.start;
|
||||
let length = overlap.end.saturating_sub(overlap.start);
|
||||
resolved_mappings.push(
|
||||
(map.dest_range.start + dest_start_idx)..(map.dest_range.start + dest_start_idx + length),
|
||||
);
|
||||
local_residual.extend_from_slice(&range_exclude(&range, &overlap));
|
||||
} else {
|
||||
local_residual.push(range);
|
||||
}
|
||||
}
|
||||
residual = local_residual;
|
||||
}
|
||||
|
||||
// unresolved maps map 1:1
|
||||
resolved_mappings.extend_from_slice(&residual);
|
||||
|
||||
resolved_mappings
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&mut Lines<'_>> for AlmanacMappingTable {
|
||||
fn from(lines: &mut Lines<'_>) -> Self {
|
||||
let name = lines.next().unwrap().split_once(':').unwrap().0.into();
|
||||
let mut mappings = Vec::new();
|
||||
for line in lines {
|
||||
if line == "" {
|
||||
break;
|
||||
}
|
||||
mappings.push(AlmanacMapping::from(line));
|
||||
}
|
||||
AlmanacMappingTable { name, mappings }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Almanac {
|
||||
seeds: Vec<i64>,
|
||||
seed_to_soil: AlmanacMappingTable,
|
||||
soil_to_fertilizer: AlmanacMappingTable,
|
||||
fertilizer_to_water: AlmanacMappingTable,
|
||||
water_to_light: AlmanacMappingTable,
|
||||
light_to_temperature: AlmanacMappingTable,
|
||||
temperature_to_humidity: AlmanacMappingTable,
|
||||
humidity_to_location: AlmanacMappingTable,
|
||||
}
|
||||
|
||||
impl From<Lines<'_>> for Almanac {
|
||||
fn from(mut lines: Lines<'_>) -> Self {
|
||||
let seeds_s = lines.next().unwrap();
|
||||
let seeds: Vec<i64> = seeds_s
|
||||
.split_once(": ")
|
||||
.unwrap()
|
||||
.1
|
||||
.split_whitespace()
|
||||
.map(|s| s.parse().unwrap())
|
||||
.collect();
|
||||
lines.next();
|
||||
|
||||
Almanac {
|
||||
seeds,
|
||||
seed_to_soil: AlmanacMappingTable::from(&mut lines),
|
||||
soil_to_fertilizer: AlmanacMappingTable::from(&mut lines),
|
||||
fertilizer_to_water: AlmanacMappingTable::from(&mut lines),
|
||||
water_to_light: AlmanacMappingTable::from(&mut lines),
|
||||
light_to_temperature: AlmanacMappingTable::from(&mut lines),
|
||||
temperature_to_humidity: AlmanacMappingTable::from(&mut lines),
|
||||
humidity_to_location: AlmanacMappingTable::from(&mut lines),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Almanac {
|
||||
fn lookup(&self, seed_id: i64) -> i64 {
|
||||
self.humidity_to_location.lookup(
|
||||
self.temperature_to_humidity.lookup(
|
||||
self.light_to_temperature.lookup(
|
||||
self.water_to_light.lookup(
|
||||
self.fertilizer_to_water
|
||||
.lookup(self.soil_to_fertilizer.lookup(self.seed_to_soil.lookup(seed_id))),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
fn lookup_range(&self, range: Range<i64>) -> Vec<Range<i64>> {
|
||||
self.humidity_to_location.lookup_ranges(
|
||||
self.temperature_to_humidity.lookup_ranges(
|
||||
self.light_to_temperature.lookup_ranges(
|
||||
self.water_to_light.lookup_ranges(
|
||||
self.fertilizer_to_water.lookup_ranges(
|
||||
self.soil_to_fertilizer
|
||||
.lookup_ranges(self.seed_to_soil.lookup_ranges(vec![range])),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// PROBLEM 1 solution
|
||||
|
||||
// The gardener and his team want to get started as soon as possible, so they'd like to
|
||||
// know the closest location that needs a seed. Using these maps, find the lowest
|
||||
// location number that corresponds to any of the initial seeds. To do this, you'll need
|
||||
// to convert each seed number through other categories until you can find its
|
||||
// corresponding location number. In this example, the corresponding types are:
|
||||
|
||||
// Seed 79, soil 81, fertilizer 81, water 81, light 74, temperature 78, humidity 78, location 82.
|
||||
// Seed 14, soil 14, fertilizer 53, water 49, light 42, temperature 42, humidity 43, location 43.
|
||||
// Seed 55, soil 57, fertilizer 57, water 53, light 46, temperature 82, humidity 82, location 86.
|
||||
// Seed 13, soil 13, fertilizer 52, water 41, light 34, temperature 34, humidity 35, location 35.
|
||||
|
||||
// So, the lowest location number in this example is 35.
|
||||
|
||||
// What is the lowest location number that corresponds to any of the initial seed numbers?
|
||||
|
||||
fn problem1_lowest_location(almanac: &Almanac) -> i64 {
|
||||
almanac.seeds.iter().map(|seed| almanac.lookup(*seed)).min().unwrap()
|
||||
}
|
||||
|
||||
#[aoc_generator(day5)]
|
||||
fn parse(input: &str) -> Almanac {
|
||||
Almanac::from(input.lines())
|
||||
}
|
||||
|
||||
#[aoc(day5, part1)]
|
||||
fn part1(almanac: &Almanac) -> i64 {
|
||||
problem1_lowest_location(almanac)
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
|
||||
// Everyone will starve if you only plant such a small number of seeds. Re-reading the
|
||||
// almanac, it looks like the seeds: line actually describes ranges of seed numbers.
|
||||
|
||||
// The values on the initial seeds: line come in pairs. Within each pair, the first
|
||||
// value is the start of the range and the second value is the length of the range. So,
|
||||
// in the first line of the example above:
|
||||
|
||||
// seeds: 79 14 55 13
|
||||
|
||||
// This line describes two ranges of seed numbers to be planted in the garden. The first
|
||||
// range starts with seed number 79 and contains 14 values: 79, 80, ..., 91, 92. The
|
||||
// second range starts with seed number 55 and contains 13 values: 55, 56, ..., 66, 67.
|
||||
|
||||
// Now, rather than considering four seed numbers, you need to consider a total of 27
|
||||
// seed numbers.
|
||||
|
||||
// In the above example, the lowest location number can be obtained from seed number 82,
|
||||
// which corresponds to soil 84, fertilizer 84, water 84, light 77, temperature 45,
|
||||
// humidity 46, and location 46. So, the lowest location number is 46.
|
||||
|
||||
// Consider all of the initial seed numbers listed in the ranges on the first line of
|
||||
// the almanac. What is the lowest location number that corresponds to any of the
|
||||
// initial seed numbers?
|
||||
|
||||
fn problem2_lowest_location(almanac: &Almanac) -> i64 {
|
||||
let seed_ranges = almanac
|
||||
.seeds
|
||||
.iter()
|
||||
.tuples()
|
||||
.map(|(range_start, length)| *range_start..*range_start + *length);
|
||||
|
||||
// seed_ranges
|
||||
// .map(|range| {
|
||||
// range
|
||||
// .into_par_iter()
|
||||
// .map(|x| almanac.lookup(x))
|
||||
// .min()
|
||||
// .unwrap()
|
||||
// })
|
||||
// .min()
|
||||
// .unwrap()
|
||||
let ranges = seed_ranges.flat_map(|range| almanac.lookup_range(range)).collect_vec();
|
||||
|
||||
ranges.iter().map(|range| range.start).min().unwrap()
|
||||
}
|
||||
|
||||
#[aoc(day5, part2)]
|
||||
fn part2(almanac: &Almanac) -> i64 {
|
||||
problem2_lowest_location(almanac)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use num::Num;
|
||||
use rstest::rstest;
|
||||
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE_ALMANAC: &str = "seeds: 79 14 55 13
|
||||
|
||||
seed-to-soil map:
|
||||
50 98 2
|
||||
52 50 48
|
||||
|
||||
soil-to-fertilizer map:
|
||||
0 15 37
|
||||
37 52 2
|
||||
39 0 15
|
||||
|
||||
fertilizer-to-water map:
|
||||
49 53 8
|
||||
0 11 42
|
||||
42 0 7
|
||||
57 7 4
|
||||
|
||||
water-to-light map:
|
||||
88 18 7
|
||||
18 25 70
|
||||
|
||||
light-to-temperature map:
|
||||
45 77 23
|
||||
81 45 19
|
||||
68 64 13
|
||||
|
||||
temperature-to-humidity map:
|
||||
0 69 1
|
||||
1 0 69
|
||||
|
||||
humidity-to-location map:
|
||||
60 56 37
|
||||
56 93 4";
|
||||
|
||||
#[test]
|
||||
fn test_almanac_mapping_parse() {
|
||||
let s = "50 98 2";
|
||||
let a = AlmanacMapping::from(s);
|
||||
assert_eq!(a.source_range, 98..100);
|
||||
assert_eq!(a.dest_range, 50..52);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_almanac_mapping_lookup() {
|
||||
let s = "50 98 2";
|
||||
let a = AlmanacMapping::from(s);
|
||||
assert_eq!(a.lookup(99), Some(51));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_almanac_parsing() {
|
||||
let a = parse(EXAMPLE_ALMANAC);
|
||||
assert_eq!(a.lookup(79), 82);
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case::one_range_overlaps_completely(0..5, 2..4, Some(2..4))]
|
||||
#[case::one_range_overlaps_from_below(0..5, 2..10, Some(2..5))]
|
||||
#[case::no_overlap_touching(0..5, 5..10, None)]
|
||||
#[case::no_overlap_disjoint(0..5, 6..10, None)]
|
||||
fn test_range_overlap<T: Num + Copy + Ord + std::fmt::Debug>(
|
||||
#[case] r1: Range<T>,
|
||||
#[case] r2: Range<T>,
|
||||
#[case] expected: Option<Range<T>>,
|
||||
) {
|
||||
assert_eq!(range_overlap(&r1, &r2), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_problem1_example() {
|
||||
let a = parse(EXAMPLE_ALMANAC);
|
||||
assert_eq!(problem1_lowest_location(&a), 35);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_problem2_example() {
|
||||
let a = parse(EXAMPLE_ALMANAC);
|
||||
assert_eq!(problem2_lowest_location(&a), 46);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
use aoc_runner_derive::aoc;
|
||||
use std::str::Lines;
|
||||
|
||||
// --- Day 6: Wait For It ---
|
||||
|
||||
// The ferry quickly brings you across Island Island. After asking around, you discover
|
||||
// that there is indeed normally a large pile of sand somewhere near here, but you don't
|
||||
// see anything besides lots of water and the small island where the ferry has docked.
|
||||
|
||||
// As you try to figure out what to do next, you notice a poster on a wall near the
|
||||
// ferry dock. "Boat races! Open to the public! Grand prize is an all-expenses-paid trip
|
||||
// to Desert Island!" That must be where the sand comes from! Best of all, the boat
|
||||
// races are starting in just a few minutes.
|
||||
|
||||
// You manage to sign up as a competitor in the boat races just in time. The organizer
|
||||
// explains that it's not really a traditional race - instead, you will get a fixed
|
||||
// amount of time during which your boat has to travel as far as it can, and you win if
|
||||
// your boat goes the farthest.
|
||||
|
||||
// As part of signing up, you get a sheet of paper (your puzzle input) that lists the
|
||||
// time allowed for each race and also the best distance ever recorded in that race. To
|
||||
// guarantee you win the grand prize, you need to make sure you go farther in each race
|
||||
// than the current record holder.
|
||||
|
||||
// The organizer brings you over to the area where the boat races are held. The boats
|
||||
// are much smaller than you expected - they're actually toy boats, each with a big
|
||||
// button on top. Holding down the button charges the boat, and releasing the button
|
||||
// allows the boat to move. Boats move faster if their button was held longer, but time
|
||||
// spent holding the button counts against the total race time. You can only hold the
|
||||
// button at the start of the race, and boats don't move until the button is released.
|
||||
|
||||
// For example:
|
||||
|
||||
// Time: 7 15 30
|
||||
// Distance: 9 40 200
|
||||
|
||||
// This document describes three races:
|
||||
|
||||
// The first race lasts 7 milliseconds. The record distance in this race is 9 millimeters.
|
||||
// The second race lasts 15 milliseconds. The record distance in this race is 40 millimeters.
|
||||
// The third race lasts 30 milliseconds. The record distance in this race is 200 millimeters.
|
||||
|
||||
// Your toy boat has a starting speed of zero millimeters per millisecond. For each
|
||||
// whole millisecond you spend at the beginning of the race holding down the button, the
|
||||
// boat's speed increases by one millimeter per millisecond.
|
||||
|
||||
// So, because the first race lasts 7 milliseconds, you only have a few options:
|
||||
|
||||
// Don't hold the button at all (that is, hold it for 0 milliseconds) at the start
|
||||
// of the race. The boat won't move; it will have traveled 0 millimeters by the end
|
||||
// of the race.
|
||||
|
||||
// Hold the button for 1 millisecond at the start of the race. Then, the boat will
|
||||
// travel at a speed of 1 millimeter per millisecond for 6 milliseconds, reaching a
|
||||
// total distance traveled of 6 millimeters.
|
||||
|
||||
// Hold the button for 2 milliseconds, giving the boat a speed of 2 millimeters per
|
||||
// millisecond. It will then get 5 milliseconds to move, reaching a total distance
|
||||
// of 10 millimeters.
|
||||
|
||||
// Hold the button for 3 milliseconds. After its remaining 4 milliseconds of travel
|
||||
// time, the boat will have gone 12 millimeters.
|
||||
|
||||
// Hold the button for 4 milliseconds. After its remaining 3 milliseconds of travel
|
||||
// time, the boat will have gone 12 millimeters.
|
||||
|
||||
// Hold the button for 5 milliseconds, causing the boat to travel a total of 10
|
||||
// millimeters.
|
||||
|
||||
// Hold the button for 6 milliseconds, causing the boat to travel a total of 6
|
||||
// millimeters.
|
||||
|
||||
// Hold the button for 7 milliseconds. That's the entire duration of the race. You
|
||||
// never let go of the button. The boat can't move until you let go of the button.
|
||||
// Please make sure you let go of the button so the boat gets to move. 0
|
||||
// millimeters.
|
||||
|
||||
// Since the current record for this race is 9 millimeters, there are actually 4
|
||||
// different ways you could win: you could hold the button for 2, 3, 4, or 5
|
||||
// milliseconds at the start of the race.
|
||||
|
||||
// In the second race, you could hold the button for at least 4 milliseconds and at most
|
||||
// 11 milliseconds and beat the record, a total of 8 different ways to win.
|
||||
|
||||
// In the third race, you could hold the button for at least 11 milliseconds and no more
|
||||
// than 19 milliseconds and still beat the record, a total of 9 ways you could win.
|
||||
|
||||
// PARSER
|
||||
|
||||
#[derive(Debug)]
|
||||
|
||||
// Appropriate for Problem 1 only
|
||||
struct Races(Vec<(u64, u64)>);
|
||||
|
||||
impl From<Lines<'_>> for Races {
|
||||
fn from(mut input: Lines<'_>) -> Self {
|
||||
let timeline = input.next().unwrap();
|
||||
let distline = input.next().unwrap();
|
||||
|
||||
let times = timeline.split_whitespace().skip(1).map(|s| s.parse().unwrap());
|
||||
let distances = distline.split_whitespace().skip(1).map(|s| s.parse().unwrap());
|
||||
|
||||
Races(times.zip(distances).collect())
|
||||
}
|
||||
}
|
||||
|
||||
// PROBLEM 1 solution
|
||||
|
||||
// To see how much margin of error you have, determine the number of ways you can beat
|
||||
// the record in each race; in this example, if you multiply these values together, you
|
||||
// get 288 (4 * 8 * 9).
|
||||
|
||||
// Determine the number of ways you could beat the record in each race. What do you get
|
||||
// if you multiply these numbers together?
|
||||
|
||||
/// Calculate the 'score' of a race. Speed will equal button duration, and runtime
|
||||
/// equals the remaining time
|
||||
fn race_distance(button_duration: u64, race_duration: u64) -> u64 {
|
||||
assert!(button_duration <= race_duration);
|
||||
|
||||
let running_time = race_duration - button_duration;
|
||||
|
||||
running_time * button_duration
|
||||
}
|
||||
|
||||
fn problem1_possible_wins(race: (u64, u64)) -> u64 {
|
||||
let (duration, record) = race;
|
||||
|
||||
(1..duration)
|
||||
.map(|button_duration| race_distance(button_duration, duration))
|
||||
.filter(|achieved_distance| *achieved_distance > record)
|
||||
.count() as u64
|
||||
}
|
||||
|
||||
#[aoc(day6, part1)]
|
||||
fn part1(input: &str) -> u64 {
|
||||
let races = Races::from(input.lines());
|
||||
races
|
||||
.0
|
||||
.iter()
|
||||
.map(|race| problem1_possible_wins(*race))
|
||||
.fold(1, |accum, elem| accum * elem)
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
|
||||
// As the race is about to start, you realize the piece of paper with race times and
|
||||
// record distances you got earlier actually just has very bad kerning. There's really
|
||||
// only one race - ignore the spaces between the numbers on each line.
|
||||
|
||||
// So, the example from before:
|
||||
|
||||
// Time: 7 15 30
|
||||
// Distance: 9 40 200
|
||||
|
||||
// ...now instead means this:
|
||||
|
||||
// Time: 71530
|
||||
// Distance: 940200
|
||||
|
||||
// Now, you have to figure out how many ways there are to win this single race. In this
|
||||
// example, the race lasts for 71530 milliseconds and the record distance you need to
|
||||
// beat is 940200 millimeters. You could hold the button anywhere from 14 to 71516
|
||||
// milliseconds and beat the record, a total of 71503 ways!
|
||||
|
||||
// How many ways can you beat the record in this one much longer race?
|
||||
|
||||
fn problem2_parse_all_digits_to_number(s: &str) -> u64 {
|
||||
s.chars()
|
||||
.filter(|c| c.is_digit(10))
|
||||
.fold(0, |accum, elem| accum * 10 + elem.to_digit(10).unwrap() as u64)
|
||||
}
|
||||
|
||||
#[aoc(day6, part2)]
|
||||
fn part2(input: &str) -> u64 {
|
||||
let mut input = input.lines();
|
||||
let time = problem2_parse_all_digits_to_number(input.next().unwrap());
|
||||
let distance = problem2_parse_all_digits_to_number(input.next().unwrap());
|
||||
|
||||
problem1_possible_wins((time, distance))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "Time: 7 15 30
|
||||
Distance: 9 40 200";
|
||||
|
||||
#[test]
|
||||
fn test_races_parser() {
|
||||
let races = Races::from(EXAMPLE.lines());
|
||||
assert_eq!(races.0, vec![(7, 9), (15, 40), (30, 200)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_race_distance() {
|
||||
assert_eq!(race_distance(0, 7), 0);
|
||||
assert_eq!(race_distance(1, 7), 6);
|
||||
assert_eq!(race_distance(2, 7), 10);
|
||||
assert_eq!(race_distance(3, 7), 12);
|
||||
assert_eq!(race_distance(7, 7), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_possible_wins() {
|
||||
assert_eq!(problem1_possible_wins((7, 9)), 4);
|
||||
assert_eq!(problem1_possible_wins((15, 40)), 8);
|
||||
assert_eq!(problem1_possible_wins((30, 200)), 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(EXAMPLE), 288);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(EXAMPLE), 71503);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
use aoc_runner_derive::aoc;
|
||||
|
||||
// PARSING
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Ord, Eq)]
|
||||
enum Card {
|
||||
TWO,
|
||||
THREE,
|
||||
FOUR,
|
||||
FIVE,
|
||||
SIX,
|
||||
SEVEN,
|
||||
EIGHT,
|
||||
NINE,
|
||||
T,
|
||||
J,
|
||||
Q,
|
||||
K,
|
||||
A,
|
||||
}
|
||||
|
||||
impl Card {
|
||||
const fn count() -> usize {
|
||||
Card::A as usize + 1
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, PartialOrd, Ord, Eq)]
|
||||
enum HandType {
|
||||
HighCard,
|
||||
OnePair,
|
||||
TwoPair,
|
||||
ThreeOfAKind,
|
||||
FullHouse,
|
||||
FourOfAKind,
|
||||
FiveOfAKind,
|
||||
}
|
||||
|
||||
impl From<char> for Card {
|
||||
fn from(c: char) -> Self {
|
||||
match c {
|
||||
'A' => Self::A,
|
||||
'K' => Self::K,
|
||||
'Q' => Self::Q,
|
||||
'J' => Self::J,
|
||||
'T' => Self::T,
|
||||
'9' => Self::NINE,
|
||||
'8' => Self::EIGHT,
|
||||
'7' => Self::SEVEN,
|
||||
'6' => Self::SIX,
|
||||
'5' => Self::FIVE,
|
||||
'4' => Self::FOUR,
|
||||
'3' => Self::THREE,
|
||||
'2' => Self::TWO,
|
||||
_ => panic!("Invalid card {}", c),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct Hand<const WILD: bool> {
|
||||
cards: Vec<Card>,
|
||||
bid: u64,
|
||||
}
|
||||
|
||||
impl<const WILD: bool> Hand<WILD> {
|
||||
fn card_counts(&self) -> [u64; Card::count()] {
|
||||
let mut counts = [0u64; Card::count()];
|
||||
for card in &self.cards {
|
||||
counts[*card as usize] += 1;
|
||||
}
|
||||
|
||||
counts
|
||||
}
|
||||
fn hand_type(&self) -> HandType {
|
||||
if !WILD {
|
||||
let card_counts = self.card_counts();
|
||||
if card_counts.contains(&5) {
|
||||
HandType::FiveOfAKind
|
||||
} else if card_counts.contains(&4) {
|
||||
HandType::FourOfAKind
|
||||
} else if card_counts.contains(&3) && card_counts.contains(&2) {
|
||||
HandType::FullHouse
|
||||
} else if card_counts.contains(&3) {
|
||||
HandType::ThreeOfAKind
|
||||
} else if card_counts.iter().filter(|count| **count == 2).count() == 2 {
|
||||
HandType::TwoPair
|
||||
} else if card_counts.contains(&2) {
|
||||
HandType::OnePair
|
||||
} else {
|
||||
HandType::HighCard
|
||||
}
|
||||
} else {
|
||||
let mut card_counts = self.card_counts();
|
||||
let wild_count = card_counts[Card::J as usize];
|
||||
card_counts[Card::J as usize] = 0;
|
||||
|
||||
let same_count = card_counts.iter().max().unwrap() + wild_count;
|
||||
|
||||
if same_count == 5 {
|
||||
HandType::FiveOfAKind
|
||||
} else if same_count == 4 {
|
||||
HandType::FourOfAKind
|
||||
} else if card_counts.contains(&3) && card_counts.contains(&2) {
|
||||
HandType::FullHouse
|
||||
} else
|
||||
// Full House with WILDs
|
||||
if wild_count == 1
|
||||
&& (card_counts.contains(&3) || (card_counts.iter().filter(|count| **count == 2).count() == 2))
|
||||
{
|
||||
HandType::FullHouse
|
||||
} else if wild_count == 2 && card_counts.contains(&2) {
|
||||
HandType::FullHouse
|
||||
} else if wild_count == 3 {
|
||||
HandType::FullHouse
|
||||
} else if same_count == 3 {
|
||||
HandType::ThreeOfAKind
|
||||
} else if card_counts.iter().filter(|count| **count == 2).count() == 2
|
||||
|| (card_counts.contains(&2) && wild_count > 0)
|
||||
{
|
||||
HandType::TwoPair
|
||||
} else if same_count == 2 {
|
||||
HandType::OnePair
|
||||
} else {
|
||||
HandType::HighCard
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<const WILD: bool> From<&str> for Hand<WILD> {
|
||||
fn from(s: &str) -> Self {
|
||||
let (cards_s, bid_s) = s.split_once(' ').unwrap();
|
||||
let bid = bid_s.parse().unwrap();
|
||||
let cards = cards_s.chars().map(|c| Card::from(c)).collect();
|
||||
|
||||
Hand { cards, bid }
|
||||
}
|
||||
}
|
||||
|
||||
impl<const WILD: bool> PartialOrd for Hand<WILD> {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl<const WILD: bool> Ord for Hand<WILD> {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
let our_type = self.hand_type();
|
||||
let other_type = other.hand_type();
|
||||
if our_type != other_type {
|
||||
our_type.cmp(&other_type)
|
||||
} else {
|
||||
let (ours, theirs) = self
|
||||
.cards
|
||||
.iter()
|
||||
.zip(other.cards.iter())
|
||||
.find(|(ours, theirs)| *ours != *theirs)
|
||||
.unwrap();
|
||||
if !WILD {
|
||||
ours.cmp(theirs)
|
||||
} else {
|
||||
if *ours == Card::J {
|
||||
std::cmp::Ordering::Less
|
||||
} else if *theirs == Card::J {
|
||||
std::cmp::Ordering::Greater
|
||||
} else {
|
||||
ours.cmp(theirs)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// PROBLEM 1 solution
|
||||
|
||||
#[aoc(day7, part1)]
|
||||
fn part1(input: &str) -> u64 {
|
||||
let mut hands: Vec<_> = input.lines().map(|line| Hand::<false>::from(line)).collect();
|
||||
hands.sort();
|
||||
hands
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(idx, hand)| (idx + 1) as u64 * hand.bid)
|
||||
.sum()
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
#[aoc(day7, part2)]
|
||||
fn part2(input: &str) -> u64 {
|
||||
let mut hands: Vec<_> = input.lines().map(|line| Hand::<true>::from(line)).collect();
|
||||
hands.sort();
|
||||
hands
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(idx, hand)| (idx + 1) as u64 * hand.bid)
|
||||
.sum()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "32T3K 765
|
||||
T55J5 684
|
||||
KK677 28
|
||||
KTJJT 220
|
||||
QQQJA 483";
|
||||
|
||||
#[test]
|
||||
fn test_hand_parser() {
|
||||
let hand = Hand::<false>::from(EXAMPLE.lines().next().unwrap());
|
||||
assert_eq!(
|
||||
hand,
|
||||
Hand {
|
||||
bid: 765,
|
||||
cards: vec![Card::THREE, Card::TWO, Card::T, Card::THREE, Card::K]
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn problem1_test_hand_compare() {
|
||||
let hand1 = Hand::<false>::from("T55J5 123");
|
||||
let hand2 = Hand::<false>::from("QQQJA 123");
|
||||
let hand3 = Hand::<false>::from("KK677 123");
|
||||
|
||||
assert!(hand2 > hand1);
|
||||
assert!(hand3 < hand1);
|
||||
assert!(hand3 < hand2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn problem2_test_hand_compare() {}
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(EXAMPLE), 6440);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(EXAMPLE), 5905);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use std::collections::HashMap;
|
||||
|
||||
use lazy_regex::{lazy_regex, Lazy, Regex};
|
||||
|
||||
// PARSE
|
||||
|
||||
const LINE_REGEX: Lazy<Regex> = lazy_regex!(r"([A-Z0-9]{3}) = \(([A-Z0-9]{3}), ([A-Z0-9]{3})\)");
|
||||
|
||||
enum Instruction {
|
||||
LEFT,
|
||||
RIGHT,
|
||||
}
|
||||
|
||||
impl From<char> for Instruction {
|
||||
fn from(c: char) -> Self {
|
||||
match c {
|
||||
'L' => Self::LEFT,
|
||||
'R' => Self::RIGHT,
|
||||
_ => panic!("Invalid instruction"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Element {
|
||||
left: String,
|
||||
right: String,
|
||||
}
|
||||
|
||||
type Nodes = HashMap<String, Element>;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Map {
|
||||
instructions: Vec<char>,
|
||||
nodes: Nodes,
|
||||
}
|
||||
|
||||
fn parse_node(nodes: &mut Nodes, node: &str) {
|
||||
let matches = LINE_REGEX.captures(node).unwrap();
|
||||
|
||||
let node_id = matches.get(1).unwrap().as_str();
|
||||
let left = matches.get(2).unwrap().as_str();
|
||||
let right = matches.get(3).unwrap().as_str();
|
||||
|
||||
nodes.insert(
|
||||
node_id.to_string(),
|
||||
Element {
|
||||
left: left.to_string(),
|
||||
right: right.to_string(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[aoc_generator(day8)]
|
||||
fn parse(input: &str) -> Map {
|
||||
let mut lines = input.lines();
|
||||
let instructions = lines.next().unwrap().chars().collect();
|
||||
let mut nodes = HashMap::new();
|
||||
lines.next();
|
||||
for line in lines {
|
||||
parse_node(&mut nodes, line);
|
||||
}
|
||||
|
||||
Map { instructions, nodes }
|
||||
}
|
||||
|
||||
// PROBLEM 1 solution
|
||||
|
||||
#[aoc(day8, part1)]
|
||||
fn part1(map: &Map) -> u64 {
|
||||
let mut count = 0;
|
||||
let mut cur_node = "AAA";
|
||||
for side in map.instructions.iter().cycle() {
|
||||
count += 1;
|
||||
cur_node = match side {
|
||||
'L' => &map.nodes[cur_node].left,
|
||||
'R' => &map.nodes[cur_node].right,
|
||||
_ => panic!("invalid instruction"),
|
||||
};
|
||||
if cur_node == "ZZZ" {
|
||||
return count;
|
||||
}
|
||||
}
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
fn node_cycle_length(map: &Map, node: &str) -> u64 {
|
||||
let mut count = 0;
|
||||
let mut cur_node = node;
|
||||
for side in map.instructions.iter().cycle() {
|
||||
count += 1;
|
||||
cur_node = match side {
|
||||
'L' => &map.nodes[cur_node].left,
|
||||
'R' => &map.nodes[cur_node].right,
|
||||
_ => panic!("invalid instruction"),
|
||||
};
|
||||
if cur_node.ends_with('Z') {
|
||||
return count;
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
#[aoc(day8, part2)]
|
||||
fn part2(map: &Map) -> u64 {
|
||||
let starting_nodes: Vec<_> = map.nodes.keys().filter(|s| s.ends_with('A')).collect();
|
||||
|
||||
starting_nodes
|
||||
.iter()
|
||||
.map(|n| node_cycle_length(map, *n))
|
||||
.fold(1, |accum, elem| num::integer::lcm(accum, elem))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "RL
|
||||
|
||||
AAA = (BBB, CCC)
|
||||
BBB = (DDD, EEE)
|
||||
CCC = (ZZZ, GGG)
|
||||
DDD = (DDD, DDD)
|
||||
EEE = (EEE, EEE)
|
||||
GGG = (GGG, GGG)
|
||||
ZZZ = (ZZZ, ZZZ)";
|
||||
|
||||
const EXAMPLE2: &str = "LR
|
||||
|
||||
11A = (11B, XXX)
|
||||
11B = (XXX, 11Z)
|
||||
11Z = (11B, XXX)
|
||||
22A = (22B, XXX)
|
||||
22B = (22C, 22C)
|
||||
22C = (22Z, 22Z)
|
||||
22Z = (22B, 22B)
|
||||
XXX = (XXX, XXX)";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(&parse(EXAMPLE)), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(&parse(EXAMPLE2)), 6);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
use aoc_runner_derive::aoc;
|
||||
use itertools::Itertools;
|
||||
|
||||
// PARSE
|
||||
|
||||
#[derive(Debug)]
|
||||
struct History(Vec<Vec<i64>>);
|
||||
|
||||
impl From<&str> for History {
|
||||
fn from(s: &str) -> Self {
|
||||
let hist: Vec<i64> = s.split_whitespace().map(|num| num.parse().unwrap()).collect();
|
||||
Self(vec![hist])
|
||||
}
|
||||
}
|
||||
|
||||
impl History {
|
||||
fn build_row(&mut self) {
|
||||
let last = self.0.last().unwrap();
|
||||
self.0.push(last.iter().tuple_windows().map(|(a, b)| b - a).collect())
|
||||
}
|
||||
|
||||
fn build(&mut self) {
|
||||
while !self.0.last().unwrap().iter().all(|x| *x == 0) {
|
||||
self.build_row();
|
||||
}
|
||||
}
|
||||
|
||||
fn extrapolate(&mut self) {
|
||||
self.build();
|
||||
self.0.last_mut().unwrap().push(0);
|
||||
for (lower, upper) in (0..self.0.len()).rev().tuple_windows() {
|
||||
let new_value = self.0[upper].last().unwrap() + self.0[lower].last().unwrap();
|
||||
self.0[upper].push(new_value);
|
||||
}
|
||||
}
|
||||
|
||||
fn extrapolate2(&mut self) {
|
||||
self.build();
|
||||
self.0.last_mut().unwrap().insert(0, 0);
|
||||
for (lower, upper) in (0..self.0.len()).rev().tuple_windows() {
|
||||
let new_value = self.0[upper].first().unwrap() - self.0[lower].first().unwrap();
|
||||
self.0[upper].insert(0, new_value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// PROBLEM 1 solution
|
||||
|
||||
#[aoc(day9, part1)]
|
||||
fn part1(input: &str) -> i64 {
|
||||
let mut histories: Vec<History> = input.lines().map(|s| History::from(s)).collect();
|
||||
|
||||
for history in &mut histories {
|
||||
history.extrapolate();
|
||||
}
|
||||
|
||||
histories
|
||||
.iter()
|
||||
.map(|history| history.0.first().unwrap().last().unwrap())
|
||||
.sum()
|
||||
}
|
||||
|
||||
// PROBLEM 2 solution
|
||||
#[aoc(day9, part2)]
|
||||
fn part2(input: &str) -> i64 {
|
||||
let mut histories: Vec<History> = input.lines().map(|s| History::from(s)).collect();
|
||||
|
||||
for history in &mut histories {
|
||||
history.extrapolate2();
|
||||
}
|
||||
|
||||
histories
|
||||
.iter()
|
||||
.map(|history| history.0.first().unwrap().first().unwrap())
|
||||
.sum()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EXAMPLE: &str = "0 3 6 9 12 15
|
||||
1 3 6 10 15 21
|
||||
10 13 16 21 30 45";
|
||||
|
||||
#[test]
|
||||
fn part1_example() {
|
||||
assert_eq!(part1(EXAMPLE), 114);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
assert_eq!(part2(EXAMPLE), 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
mod day1;
|
||||
mod day10;
|
||||
mod day11;
|
||||
mod day12;
|
||||
mod day13;
|
||||
mod day14;
|
||||
mod day15;
|
||||
mod day16;
|
||||
mod day17;
|
||||
mod day18;
|
||||
mod day19;
|
||||
mod day2;
|
||||
mod day20;
|
||||
mod day21;
|
||||
mod day22;
|
||||
mod day23;
|
||||
mod day24;
|
||||
mod day25;
|
||||
mod day3;
|
||||
mod day4;
|
||||
mod day5;
|
||||
mod day6;
|
||||
mod day7;
|
||||
mod day8;
|
||||
mod day9;
|
||||
|
||||
use aoc_runner_derive::aoc_lib;
|
||||
|
||||
aoc_lib! { year = 2023 }
|
||||
@@ -0,0 +1,3 @@
|
||||
use aoc_runner_derive::aoc_main;
|
||||
|
||||
aoc_main! { lib = aoc2023 }
|
||||
Reference in new issue
Block a user