Rust:codewars count of Positives/sum of Negatives_rust

Source: Internet
Author: User

This problem is very easy, but there are some usages that we can learn.

Topic Requirements:

Find the number of positive numbers in a vector, and the number of negative numbers.

First, the solution

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

I also made some efforts to one-step, but did not succeed.

Such as:

The following are non valid code attempts 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,
    })
}
The following are non valid code attempts 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,
    })
}

In fact, try 2 Some quick close to success ...

Using the solution of other people in Codewars, we can run the
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
    })
}

Second, the Codewars wonderful solution
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 ()} 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.