51: replace skip with skip_while

This commit is contained in:
Dr. Matthias Ratajczak
2022-08-30 17:40:04 +02:00
parent 2f6c1ef96b
commit e3c5151a82
2 changed files with 8 additions and 9 deletions
+7 -8
View File
@@ -5,6 +5,7 @@ use std::fmt::Display;
use std::fs::File; use std::fs::File;
use std::hash::Hash; use std::hash::Hash;
use std::io::Write; use std::io::Write;
use std::slice::Iter;
use num::FromPrimitive; use num::FromPrimitive;
use num::Num; use num::Num;
@@ -12,7 +13,7 @@ use num::ToPrimitive;
#[derive(Clone)] #[derive(Clone)]
pub struct Primes<T> { pub struct Primes<T> {
pub vector: Vec<T>, vector: Vec<T>,
set: HashSet<T>, set: HashSet<T>,
} }
@@ -58,9 +59,7 @@ where
let upper_limit = Self::calc_upper_limit(max_value); let upper_limit = Self::calc_upper_limit(max_value);
for i in 2..upper_limit { for i in 2..upper_limit {
let skip = Self::find_number_to_skip_until_min_value(min_value, i); for multiple in (i * i..max_value).step_by(i).skip_while(|i| i < &min_value) {
for multiple in (i * i..max_value).step_by(i).skip(skip) {
let idx = multiple - min_value; let idx = multiple - min_value;
// SAFETY: `multiple` will always be between min_value and max_value // SAFETY: `multiple` will always be between min_value and max_value
// (which define the length of the array), therfore idx is always smaller than the // (which define the length of the array), therfore idx is always smaller than the
@@ -76,10 +75,6 @@ where
f64::sqrt(max_value as f64).ceil() as usize f64::sqrt(max_value as f64).ceil() as usize
} }
fn find_number_to_skip_until_min_value(min_value: usize, i: usize) -> usize {
((min_value.saturating_sub(i * i)) as f64 / i as f64).ceil() as usize
}
pub fn remove(&mut self, num: &T) { pub fn remove(&mut self, num: &T) {
if let Some(index) = self.vector.iter().position(|x| x == num) { if let Some(index) = self.vector.iter().position(|x| x == num) {
self.vector.remove(index); self.vector.remove(index);
@@ -107,6 +102,10 @@ where
writeln!(f, "{p}").unwrap(); writeln!(f, "{p}").unwrap();
} }
} }
pub fn iter(&self) -> Iter<T> {
self.vector.iter()
}
} }
#[cfg(test)] #[cfg(test)]
+1 -1
View File
@@ -44,7 +44,7 @@ fn main() {
MAX_PATTERN_LENGTH, MAX_PATTERN_LENGTH,
AMOUNT_OF_DIGITS_IN_NUMBER, AMOUNT_OF_DIGITS_IN_NUMBER,
) { ) {
for prime in &all_primes.vector { for prime in all_primes.iter() {
primes_matching_pattern.clear(); primes_matching_pattern.clear();
let digits = prime.to_digits(); let digits = prime.to_digits();