英文:
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;
}
然而,这并不适用于创建交替的true
和false
序列。我该如何实现这个目标?
注意: 我知道在这种情况下这不会对性能产生巨大影响,但我觉得这是一个有趣的问题,而且我怀疑可能存在某些情况下这会产生影响。
<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<bool> = 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<_> = 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
你可以使用 cycle
、take
和 collect
来完成:
let mut sieve: Vec<_> = [false, true].into_iter().cycle().take(capacity).collect();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论