MST

星途 面试题库

面试题:复杂Rust数据处理流程与迭代器自定义扩展

假设有一个自定义结构体`Point { x: f64, y: f64 }`的`Vec<Point>`,你需要构建一个迭代器链,首先根据`x`坐标对`Point`进行排序,然后筛选出`y`坐标大于某个给定阈值的点,接着计算这些点到原点`(0, 0)`的距离,最后根据距离进行分组(例如,距离小于1.0的为一组,1.0到2.0为一组等)。请编写Rust代码实现该复杂数据处理流程,并且要求自定义迭代器扩展方法来完成部分功能,以展示对Rust迭代器特性的深入理解和运用。
42.6万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
use std::iter::Iterator;

// 定义结构体
struct Point {
    x: f64,
    y: f64,
}

// 自定义迭代器扩展方法
trait PointIterExt: Iterator<Item = Point> {
    fn filter_by_y(&mut self, threshold: f64) -> impl Iterator<Item = Point> {
        self.filter(move |point| point.y > threshold)
    }

    fn calculate_distance(&mut self) -> impl Iterator<Item = f64> {
        self.map(|point| (point.x.powi(2) + point.y.powi(2)).sqrt())
    }

    fn group_by_distance(&mut self) -> Vec<Vec<f64>> {
        let mut groups = Vec::new();
        for distance in self {
            let group_index = (distance / 1.0) as usize;
            if group_index >= groups.len() {
                groups.resize(group_index + 1, Vec::new());
            }
            groups[group_index].push(distance);
        }
        groups
    }
}

impl<I: Iterator<Item = Point>> PointIterExt for I {}

fn main() {
    let points: Vec<Point> = vec![
        Point { x: 1.0, y: 1.0 },
        Point { x: 2.0, y: 2.0 },
        Point { x: 0.5, y: 0.5 },
        Point { x: 1.5, y: 0.8 },
    ];
    let threshold = 1.0;

    let result = points.iter()
        .cloned()
        .sorted_by_key(|point| point.x)
        .filter_by_y(threshold)
        .calculate_distance()
        .group_by_distance();

    println!("{:?}", result);
}