1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#![deny(warnings, missing_docs)]
extern crate fxhash;
use fxhash::FxHashSet;
pub struct Recaman {
current: u64,
step: u64,
hits: FxHashSet<u64>,
}
impl Recaman {
pub fn new() -> Self {
let mut hits = FxHashSet::default();
hits.insert(0);
Recaman {
current: 0,
step: 0,
hits,
}
}
#[inline]
fn look_ahead(&self) -> u64 {
if self.current < self.step {
return 0;
}
self.current - self.step
}
}
impl Iterator for Recaman {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
self.hits.insert(self.current);
let next = self.look_ahead();
self.current = match next == 0 || self.hits.contains(&next) {
true => self.current + self.step,
false => next,
};
self.step += 1;
Some(self.current)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn initial_zero() {
let mut recaman = Recaman::new();
assert_eq!(0, recaman.next().unwrap())
}
#[test]
fn first_ten() {
let recaman = Recaman::new();
assert_eq!(
vec![0, 1, 3, 6, 2, 7, 13, 20, 12, 21],
recaman.take(10).collect::<Vec<u64>>()
)
}
}