如何基于重复序列构建一个向量?

huangapple go评论82阅读模式
英文:

How to construct a vector based on a repeating sequence?

问题

我正在编写埃拉托斯特尼筛法,为此你想要用奇数索引`true`和偶数索引`false`来开始一个布尔向量。目前我用以下代码来实现这个目标:

```rust
let mut is_prime: Vec<bool> = vec![true; capacity];
for i in (3..capacity).step_by(2) {
    is_prime[i] = false;
}

然而,这并不适用于创建交替的truefalse序列。我该如何实现这个目标?

注意: 我知道在这种情况下这不会对性能产生巨大影响,但我觉得这是一个有趣的问题,而且我怀疑可能存在某些情况下这会产生影响。


<details>
<summary>英文:</summary>

I am writing a sieve of Eratosthenes, for this you want to start a vector of booleans with odd indices `true` and even indices `false`. Currently my code for getting that is:

``` rust
let mut is_prime: Vec&lt;bool&gt; = vec![true; capacity];
is_prime.iter_mut().step_by(2).for_each(|m| *m = false);

However that doesn't work to create an alternating true false sequence. How can I achieve this?

Note: I know this won't have a massive impact on performance in this case, I but I thought it was an interesting problem and suspect there may be cases where it would make a difference.

答案1

得分: 6

你可以结合一些迭代器工具来高效、方便地完成这个任务:

let mut is_prime: Vec<_> = std::iter::repeat([true, false])
    .flatten()
    .take(capacity)
    .collect();

注意迭代器确切知道它的长度,这使得 collect 能够提前分配足够的容量来构建一个向量。

英文:

You can combine a few iterator utilities to do this efficiently and ergonomically:

let mut is_prime: Vec&lt;_&gt; = std::iter::repeat([true, false])
    .flatten()
    .take(capacity)
    .collect();

Note the iterator exactly knows its length, which allows collect to build a vector with enough capacity allocated in advance.

答案2

得分: 5

你可以使用 cycletakecollect 来完成:

let mut sieve: Vec<_> = [false, true].into_iter().cycle().take(capacity).collect();

Playground

英文:

You can do it with cycle, take and collect:

let mut sieve: Vec&lt;_&gt; = [ false, true ].into_iter().cycle().take (capacity).collect();

Playground

huangapple
  • 本文由 发表于 2023年4月4日 16:48:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75927308.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定