From 4b8c4729a52ec16abf5da3a6608fbe480e3e3f79 Mon Sep 17 00:00:00 2001 From: "Dr. Matthias Ratajczak" Date: Thu, 11 Aug 2022 14:16:40 +0200 Subject: [PATCH] add more code for 51 (WIP) --- euler51/src/main.rs | 28 +++++++++++++++++++++------- euler51/src/primes.rs | 9 ++++++--- 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/euler51/src/main.rs b/euler51/src/main.rs index 9e035f2..3db9638 100644 --- a/euler51/src/main.rs +++ b/euler51/src/main.rs @@ -14,8 +14,9 @@ const DIGITS: [Int; 10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; fn main() { let primes = Primes::get_between(MIN_VALUE, MAX_VALUE); + // let mut new_primes = primes.clone(); println!("{}", primes.vector[0]); - for p in primes.vector { + for p in primes.vector.iter() { let mut candidates = vec![]; let digits = num_to_digits(p); for d in DIGITS { @@ -27,14 +28,21 @@ fn main() { candidates.push(num) } } - println!("candidates"); - for c in candidates { - println!("{c}"); + if candidates.len() > 4 { + println!("candidates"); + for c in &candidates { + // new_primes.remove(c); + println!("{c}"); + } } } + // println!("new primes"); + // for p in new_primes.vector.iter() { + // println!("{p}"); + // } } -fn num_to_digits(n: Int) -> Vec { +fn num_to_digits(n: &Int) -> Vec { n.to_string() .chars() .map(|x| x.to_digit(10).unwrap() as Int) @@ -53,7 +61,7 @@ fn digits_to_num(vec: Vec) -> Int { #[cfg(test)] mod test { - use crate::{digits_to_num, num_to_digits}; + use crate::{digits_to_num, num_to_digits, primes::Primes, Int, MAX_VALUE, MIN_VALUE}; #[test] fn test_digits_to_num() { @@ -64,6 +72,12 @@ mod test { #[test] fn test_num_to_digits() { let num = 83371; - assert_eq!(num_to_digits(num), vec![8, 3, 3, 7, 1]); + assert_eq!(num_to_digits(&num), vec![8, 3, 3, 7, 1]); + } + + #[test] + fn test_example_prime() { + let num: Int = 56003; + assert!(Primes::get_between(MIN_VALUE, MAX_VALUE).set.contains(&num)); } } diff --git a/euler51/src/primes.rs b/euler51/src/primes.rs index 6bd5047..f917140 100644 --- a/euler51/src/primes.rs +++ b/euler51/src/primes.rs @@ -6,6 +6,7 @@ use num::ToPrimitive; use std::collections::HashSet; use std::hash::Hash; +#[derive(Clone)] pub struct Primes { pub vector: Vec, pub set: HashSet, @@ -58,8 +59,10 @@ impl Primes result } - pub fn remove(&mut self, num: T) { - let index = self.vector.iter().position(|x| x == &num).unwrap(); - self.vector.remove(index); + pub fn remove(&mut self, num: &T) { + if let Some(index) = self.vector.iter().position(|x| x == num) { + self.vector.remove(index); + self.set.remove(num); + }; } }