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()}
阅读全文
0 0
- Rust: codewars 的Count of positives / sum of negatives
- Rust : codewars的Sum of Pairs
- Rust : codewars的Product of consecutive Fib numbers
- Rust: codewars的Sum by Factors
- [Haskell] CodeWars|Sum of Digits
- CodeWars:Sum of odd numbers
- [Haskell] CodeWars|Sum of odd numbers
- Count of Range Sum
- True(False) Positives (Negatives) 的含义和翻译
- True(False) Positives (Negatives) 的含义和翻译
- True(False) Positives (Negatives) 的含义和翻译
- Rust: codewars 的Duplicate Encoder
- Rust: codewars的Bleatrix Trotter
- leetcode Count of Range Sum
- 327Count of Range Sum
- LeetCode Count of Range Sum
- [LeetCode]Count of Range Sum
- 327. Count of Range Sum
- <c语言>如何将数组初始化为0?
- 客户端向HDFS读写数据机制
- STM32系统定时器SysTick
- Unity3D-Unity中CacheServer(缓存服务器)的部署与使用
- Bringing up interface Auto_eth1: Error: No suitable device found: no device found for connection 'A
- Rust: codewars 的Count of positives / sum of negatives
- Java语言发展史
- 513. Find Bottom Left Tree Value Difficulty : mediate
- [171004]MUI多次初始化“上拉加载”的示例
- 火车头采集器对接织梦cms图集发布时, 采集网上图片超时的解决方法
- Linux-4.9.2内核在mini2440上的移植(十三)——按键驱动移植
- 成长里程1:为什么使用Struts将得到的map打包成json时,客户端会报错。
- Gym 101243 I Land Division[计算几何]
- VMwareWorkstation10 中安装Centos6.5