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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
use rayon::prelude::*;
use std::io;
use std::io::prelude::*;
use std::iter;
use std::num::ParseIntError;
use std::process;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(name = "Day 16: Flawed Frequency Transmission")]
/// Performs the flawed frequency transform of a number.
///
/// See https://adventofcode.com/2019/day/16 for details.
struct Opt {
/// the offset after which you start reading output
#[structopt(short = "o", long = "offset", default_value = "0")]
offset: usize,
input_repeats: usize,
fft_repeats: usize,
}
fn main() {
let stdin = io::stdin();
let opt = Opt::from_args();
stdin
.lock()
.lines()
.map(|x| exit_on_failed_assertion(x, "Error reading input"))
.map(|x| exit_on_failed_assertion(parse(&x), "Input was not a valid recipe"))
.for_each(|input| {
println!(
"{}",
transform(input, opt.input_repeats, opt.fft_repeats, opt.offset)
.into_iter()
.map(|c| c.to_string())
.collect::<String>()
);
});
}
fn exit_on_failed_assertion<A, E: std::error::Error>(data: Result<A, E>, message: &str) -> A {
match data {
Ok(data) => data,
Err(e) => {
eprintln!("{}: {}", message, e);
process::exit(1);
}
}
}
fn parse(s: &str) -> Result<Vec<i32>, ParseIntError> {
s.chars().map(|c| c.to_string().parse::<i32>()).collect()
}
fn transform(input: Vec<i32>, input_repeats: usize, fft_repeats: usize, offset: usize) -> Vec<i32> {
iter::successors(
Some(
input
.iter()
.cycle()
.take(input.len() * input_repeats)
.cloned()
.collect::<Vec<i32>>(),
),
|input| Some(next_phase(input, offset)),
)
.nth(fft_repeats)
.unwrap()
.into_iter()
.skip(offset)
.take(8)
.collect()
}
fn next_phase(input: &Vec<i32>, offset: usize) -> Vec<i32> {
if offset > input.len() / 2 {
(0..input.len())
.into_par_iter()
.map(|digit| {
if digit < offset {
0
} else {
input.iter().skip(digit).sum::<i32>().abs() % 10
}
})
.collect()
} else {
(0..input.len())
.into_par_iter()
.map(|digit| {
input
.iter()
.zip(pattern(digit))
.map(|(x, y)| x * y)
.sum::<i32>()
.abs()
% 10
})
.collect()
}
}
fn pattern(digit: usize) -> impl Iterator<Item = i32> {
iter::repeat(0)
.take(digit + 1)
.chain(iter::repeat(1).take(digit + 1))
.chain(iter::repeat(0).take(digit + 1))
.chain(iter::repeat(-1).take(digit + 1))
.cycle()
.skip(1)
}
|