Rust: codewars 的Count of positives / sum of negatives

30 篇文章 0 订阅

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

题目要求:

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

一、解法

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]
}

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

如:

//以下是非有效代码 尝试1
fn 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,
    })
}
//以下是非有效代码 尝试2
fn 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()
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值