This commit is contained in:
2022-12-20 20:39:38 +01:00
parent 7c6b17c3e2
commit 5406dfa6f8
5 changed files with 5086 additions and 0 deletions

5000
inputs/day20.txt Normal file

File diff suppressed because it is too large Load Diff

8
src/bin/day20_1.rs Normal file
View File

@@ -0,0 +1,8 @@
use std::fs;
use aoc2022::day20::process_part_1;
fn main() {
let file = fs::read_to_string("./inputs/day20.txt").unwrap();
println!("{}", process_part_1(&file));
}

8
src/bin/day20_2.rs Normal file
View File

@@ -0,0 +1,8 @@
use std::fs;
use aoc2022::day20::process_part_2;
fn main() {
let file = fs::read_to_string("./inputs/day20.txt").unwrap();
println!("{}", process_part_2(&file));
}

69
src/day20.rs Normal file
View File

@@ -0,0 +1,69 @@
use itertools::Itertools;
use nom::character::complete;
use nom::character::complete::newline;
use nom::multi::separated_list1;
use nom::IResult;
pub fn process_part_1(input: &str) -> i64 {
let values = parse_input(input).unwrap().1;
let mixed = mix(&values, 1);
let zero_pos = mixed.iter().position(|&v| v == 0).unwrap();
[1000, 2000, 3000]
.into_iter()
.map(|pos| mixed[(zero_pos + pos) % mixed.len()])
.sum()
}
pub fn process_part_2(input: &str) -> i64 {
let values = parse_input(input).unwrap().1;
let values = values.into_iter().map(|v| v * 811589153).collect_vec();
let mixed = mix(&values, 10);
let zero_pos = mixed.iter().position(|&v| v == 0).unwrap();
[1000, 2000, 3000]
.into_iter()
.map(|pos| mixed[(zero_pos + pos) % mixed.len()])
.sum()
}
fn mix(values: &[i64], rounds: usize) -> Vec<i64> {
let mut indices = (0..values.len()).collect::<Vec<_>>();
for _ in 0..rounds {
for (i, &v) in values.iter().enumerate() {
let pos = indices.iter().position(|&index| index == i).unwrap();
let removed = indices.remove(pos);
let new_pos = ((pos as i64) + v).rem_euclid(values.len() as i64 - 1) as usize;
indices.insert(new_pos, removed);
}
}
// reconstruct using mixed indices
indices.iter().map(|&i| values[i]).collect()
}
fn parse_input(input: &str) -> IResult<&str, Vec<i64>> {
separated_list1(newline, complete::i64)(input)
}
#[cfg(test)]
mod tests {
use super::*;
const INPUT: &str = "1
2
-3
3
-2
0
4";
#[test]
fn day1() {
assert_eq!(process_part_1(INPUT), 3);
}
#[test]
fn day2() {
assert_eq!(process_part_2(INPUT), 1623178306);
}
}

View File

@@ -20,3 +20,4 @@ pub mod day16;
pub mod day17;
pub mod day18;
pub mod day19;
pub mod day20;