-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.rs
90 lines (76 loc) · 2.58 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
use std::{collections::VecDeque, str::FromStr};
use anyhow::{Context, Result};
use itertools::Itertools;
#[aoc_generator(day20)]
pub fn input_generator(input: &str) -> Result<Vec<isize>> {
input
.lines()
.filter(|s| !s.is_empty())
.map(|s| Ok(isize::from_str(s)?))
.collect::<Result<Vec<_>>>()
.context("Error while parsing input")
}
fn mix(input: &[isize], repeat: usize) -> Result<Vec<isize>> {
let mut with_indexes = input
.iter()
.cloned()
.enumerate()
.map(|(i, v)| (i, v))
.collect::<VecDeque<_>>();
let len = input.len() as isize;
for _ in 0..repeat {
for index in 0..input.len() {
let (index_to_move, _) = with_indexes
.iter()
.find_position(|(i, _)| *i == index)
.context("element not found")?;
let element = with_indexes
.remove(index_to_move)
.context("could not remove")?;
let shift = element.1;
let mut index_to_move_to = (index_to_move as isize) + shift;
if index_to_move_to < 0 {
let factor = (index_to_move_to / (len - 1) + 1).abs();
index_to_move_to += factor * (len - 1);
}
while index_to_move_to < 0 {
index_to_move_to += len - 1;
}
if index_to_move_to >= len {
let factor = index_to_move_to / (len - 1);
index_to_move_to -= factor * (len - 1);
}
while index_to_move_to >= len {
index_to_move_to -= len - 1;
}
if index_to_move_to == 0 {
index_to_move_to = len - 1;
}
with_indexes.insert(index_to_move_to as usize, element);
}
}
Ok(with_indexes.into_iter().map(|(_, v)| v).collect::<Vec<_>>())
}
fn hash(mixed: &[isize]) -> Result<isize> {
let len = mixed.len();
let (index, _) = mixed
.iter()
.find_position(|v| **v == 0)
.context("Could not find 0")?;
let a = mixed[(index + 1000) % len as usize];
let b = mixed[(index + 2000) % len as usize];
let c = mixed[(index + 3000) % len as usize];
Ok(a + b + c)
}
#[aoc(day20, part1)]
pub fn solve_part1(input: &[isize]) -> Result<isize> {
let mixed = mix(input, 1)?;
hash(&mixed)
}
#[aoc(day20, part2)]
pub fn solve_part2(input: &[isize]) -> Result<isize> {
const FOO: isize = 811589153;
let input = input.iter().map(|v| *v * FOO).collect::<Vec<_>>();
let mixed = mix(&input, 10)?;
hash(&mixed)
}