我遇到了这个竞争性编程问题:
nums
是一个整数向量(长度n
)ops
是包含+
和-
(长度n-1
)的字符串向量它可以通过Kotlin中的reduce
操作来解决,如下所示:
val op_iter = ops.iterator();
nums.reduce {a, b ->
when (op_iter.next()) {
"+" -> a+b
"-" -> a-b
else -> throw Exception()
}
}
reduce
被描述为:
从第一个元素开始累积值,并从左到右应用操作到当前累加器值和每个元素。
看起来Rust矢量没有reduce
方法。你将如何完成这项任务?
Kotlin的reduce
将迭代器的第一项作为起点,而Rust的fold
和try_fold
则允许您指定自定义起点。
这是Kotlin代码的等价物:
let mut it = nums.iter().cloned();
let start = it.next().unwrap();
it.zip(ops.iter()).try_fold(start, |a, (b, op)| match op {
'+' => Ok(a + b),
'-' => Ok(a - b),
_ => Err(()),
})
或者因为我们从矢量开始,可以索引:
nums[1..]
.iter()
.zip(ops.iter())
.try_fold(nums[0], |a, (b, op)| match op {
'+' => Ok(a + b),
'-' => Ok(a - b),
_ => Err(()),
});