rust sort

python;gutter:true; use std::cmp::Ordering;</p> <p>enum Fruit { Apple(i32), Orange(i32), }</p> <p>fn process_fruit(_apple_prices: &[i32], _orange_prices: &[i32]) { // whatever we do to process fruit, does not matter }</p> <p>fn main() { let mut fruit : Vec = vec![Fruit::Apple(1), Fruit::Apple(2), Fruit::Orange(4), Fruit::Orange(3), ];</p> <pre><code>/* * Sort fruit by some crazy function - let's say we value oranges more * than apples, so when we compare one to the other, we increase * the price of oranges by 10. */ let fruit_comparator = |x: &Fruit, y: &Fruit| match(x, y) { (Fruit::Apple(lhs), Fruit::Apple(rhs)) => { lhs.cmp(rhs) }, (Fruit::Apple(lhs), Fruit::Orange(rhs)) => { lhs.cmp(&(*rhs + 10)) }, (Fruit::Orange(lhs), Fruit::Apple(rhs)) => { (lhs + 10).cmp(rhs) }, (Fruit::Orange(lhs), Fruit::Orange(rhs)) => { lhs.cmp(rhs) }, }; fruit.sort_by(fruit_comparator); // apples must __only__ contain Fruit::Apple variants let mut apple_prices : Vec = vec![]; // oranges must __only__ contain Fruit::Orange variants let mut orange_prices : Vec = vec![]; // TODO generate fruit_grouped from an existing sorted let fruit_sorted_by_price_grouped : Vec> = { let mut groups = Vec::new(); let mut this_group = Vec::new(); for f in fruit { if this_group.is_empty() || fruit_comparator(&this_group[0], &f) == Ordering::Equal { this_group.push(f); } else { groups.push(this_group); this_group = vec![f]; } } groups }; for i in fruit_sorted_by_price_grouped { for j in i { match j { Fruit::Apple(price) => { apple_prices.push(price); } Fruit::Orange(price) => { orange_prices.push(price); } }; process_fruit(&apple_prices, &orange_prices); apple_prices = vec![]; orange_prices = vec![]; } } </code></pre> <p>}

Original: https://www.cnblogs.com/pythonClub/p/16539508.html
Author: CrossPython
Title: rust sort

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/15772/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

发表回复

登录后才能评论
免费咨询
免费咨询
扫码关注
扫码关注
联系站长

站长Johngo!

大数据和算法重度研究者!

持续产出大数据、算法、LeetCode干货,以及业界好资源!

2022012703491714

微信来撩,免费咨询:xiaozhu_tec

分享本页
返回顶部