原题
--- Part Two ---
Considering every single measurement isn't as useful as you expected: there's just too much noise in the data.
Instead, consider sums of a three-measurement sliding window. Again considering the above example:
199 A
200 A B
208 A B C
210 B C D
200 E C D
207 E F D
240 E F G
269 F G H
260 G H
263 H
Start by comparing the first and second three-measurement windows. The measurements in the first window are marked A (199, 200, 208); their sum is 199 + 200 + 208 = 607. The second window is marked B (200, 208, 210); its sum is 618. The sum of measurements in the second window is larger than the sum of the first, so this first comparison increased.
Your goal now is to count the number of times the sum of measurements in this sliding window increases from the previous sum. So, compare A with B, then compare B with C, then C with D, and so on. Stop when there aren't enough measurements left to create a new three-measurement sum.
In the above example, the sum of each three-measurement window is as follows:
- A: 607 (N/A - no previous sum)
- B: 618 (increased)
- C: 618 (no change)
- D: 617 (decreased)
- E: 647 (increased)
- F: 716 (increased)
- G: 769 (increased)
- H: 792 (increased) In this example, there are 5 sums that are larger than the previous sum.
Consider sums of a three-measurement sliding window. How many sums are larger than the previous sum?
Answer:
解析
计算滑动窗口3个数之和,统计后一个数比前一个数大的数量
Rust实现
use std::{fs::File, io::Read};
fn main() {
// 1. 读取文件
let mut file = File::open("./day01b/input.txt").unwrap();
let mut content = String::new();
file.read_to_string(&mut content).unwrap();
// 2. 把文件内容转成数组
let inputs = content
.split("\n")
.map(|x| x.parse::<i32>().unwrap())
.collect::<Vec<i32>>();
// 3. 遍历数组计算滑动窗口3个数之和
let mut windows = vec![];
for i in 2..inputs.len() {
windows.push(inputs[i] + inputs[i - 1] + inputs[i - 2]);
}
// 4. 遍历窗口数组,计算后一个数比前一个数大的数量
let mut count = 0;
for i in 1..windows.len() {
if windows[i] > windows[i - 1] {
count += 1;
}
}
println!("Answer: {:?}", count);
}
学习
使用itertools库,参考自alexander-novo/Advent2021 (github.com)
use itertools::Itertools;
use std::fs::File;
use std::io::{self, BufRead};
fn main() {
let file = File::open("../01-1/input.txt").expect("Could not read input.txt");
let depths = io::BufReader::new(file)
.lines()
.map(|line| line.unwrap().parse::<i32>().unwrap())
// This is the only change from previous - now we are grouping by 3 and summing before comparing.
// It's funny that I just happened to pick the sliding window technique when the second project of the day involved a sliding window.
.tuple_windows()
// Unfortunately, there doesn't seem to be a great syntax for summing over Tuples,
// which makes sense (since tuples are for heterogeneous data) and itertools is only using tuples for convenience.
.map(|(a, b, c)| a + b + c)
.tuple_windows()
.filter(|(prev, next)| next > prev)
.count();
println!("{}", depths)
}
\