Rust: codewars 的Count of positives / sum of negatives

来源:互联网 发布:centos创建文件夹命令 编辑:程序博客网 时间:2024/06/05 15:27

这道题非常容易,但是,有一些用法值得我们学习。

题目要求:

求一个数字向量中正数的个数,以及负数的和。

一、解法

fn count_positives_sum_negatives(input: Vec<i32>) -> Vec<i32> {    let _up =        input.iter().filter(|&x| *x > 0).collect::<Vec<_>>().iter().fold(0, |total, &x| total + x);    let _down =        input.iter().filter(|&x| *x < 0).collect::<Vec<_>>().iter().fold(0, |total, &x| total + x);    vec![_up, _down]}

我也进行了一些努力,想一步到位,但是没有成功。

如:

//以下是非有效代码 尝试1fn count_positives_sum_negatives2(input: Vec<i32>) -> Vec<i32> {    input.iter().fold((0, 0), |(mut total, mut num), &x| match x > 0 {        true => total += 1,        _ => num += x,    })}
//以下是非有效代码 尝试2fn count_positives_sum_negatives2(input: Vec<i32>) -> Vec<i32> {    input.iter().fold((0, 0), |mut total, &x| match x > 0 {        true => total.0 += 1,        _ => total.1 += x,    })}

其实,尝试2有些快接近成功了……

//借鉴了codewars中其它人的解法,可以正确运行fn count_positives_sum_negatives2(input: Vec<i32>) -> Vec<i32> {    input.iter().fold(vec![0, 0], |mut total, &x| {        match x > 0 {            true => total[0] += 1,            _ => total[1] += x,        }        total    })}

二、codewars精彩的解法
1、

fn count_positives_sum_negatives(input: Vec<i32>) -> Vec<i32> {  if input.is_empty() {    return vec![];  }  input.iter().fold(vec![0, 0], |mut acc, &x| {      if x > 0 {        acc[0] += 1;      } else {        acc[1] += x;      }      acc  })}

2、

fn count_positives_sum_negatives(input: Vec<i32>) -> Vec<i32> {  if input.len() == 0 {    return Vec::new()  }  input.into_iter().fold([0,0], |mut sum, i| {    if i > 0 {      sum[0] += 1    } else if i < 0 {      sum[1] += i    }    sum  }).as_ref().into()}