-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleading_ones.rs
41 lines (35 loc) · 854 Bytes
/
leading_ones.rs
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
use super::Function;
use bit_vec::BitVec;
use std::fmt::Display;
#[derive(Debug, Clone, Copy)]
pub struct LeadingOnes {
n: usize,
}
impl LeadingOnes {
pub fn new(n: usize) -> LeadingOnes {
LeadingOnes { n }
}
}
impl Display for LeadingOnes {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "LeadingOnes(n = {})", self.n)
}
}
impl Function for LeadingOnes {
fn n(&self) -> usize {
self.n
}
fn fitness(&self, bitvec: &BitVec) -> i64 {
if self.n <= u32::BITS as usize {
bitvec.storage()[0].leading_ones() as i64
} else {
bitvec
.iter()
.position(|x| !x)
.unwrap_or_else(|| bitvec.len()) as i64
}
}
fn best_fitness(&self) -> i64 {
self.n as i64
}
}