From 94d9d406e640844da159b1f4f676d11986cb4cb3 Mon Sep 17 00:00:00 2001 From: timeshifter Date: Sun, 14 Aug 2022 22:03:23 +0200 Subject: [PATCH] refactor 51 --- .gitignore | 3 +++ src/euler51/Cargo.toml | 3 +++ src/euler51/src/main.rs | 38 +++++++++++++++++++++++++++++++------- 3 files changed, 37 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index c66f9e0..154e418 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ +flamegraph.svg +perf.data +perf.data.old # Created by https://www.toptal.com/developers/gitignore/api/rust,intellij,python # Edit at https://www.toptal.com/developers/gitignore?templates=rust,intellij,python diff --git a/src/euler51/Cargo.toml b/src/euler51/Cargo.toml index 69cc7b0..53ee0bb 100644 --- a/src/euler51/Cargo.toml +++ b/src/euler51/Cargo.toml @@ -8,3 +8,6 @@ edition = "2021" [dependencies] primes = {version = "*", path = "../../lib/primes"} combination = {version = "*", path = "../../lib/combination"} + +[profile.release] +debug = true diff --git a/src/euler51/src/main.rs b/src/euler51/src/main.rs index b4162a8..f52d0a5 100644 --- a/src/euler51/src/main.rs +++ b/src/euler51/src/main.rs @@ -43,12 +43,7 @@ fn main() { let mut primes_matching_pattern = vec![]; let digits = first.to_digits(); for digit in DIGITS { - let could_be_prime = digits - .iter() - .zip(pattern.clone()) - .map(|(d, b)| if b { digit } else { *d }) - .collect::>() - .to_num(); + let could_be_prime = apply_transformation(&digits, digit, &pattern); if primes_to_check.contains(&could_be_prime) || could_be_prime == first { primes_matching_pattern.push(could_be_prime); } @@ -64,6 +59,24 @@ fn main() { println!("{:#?}", get_longest(best_of_all_combinations, false)); } +fn apply_transformation(prime_as_digits: &[u8], new_digit: u8, pattern: &[bool]) -> Int { + debug_assert_eq!(prime_as_digits.len(), pattern.len()); + let mut multiplier = 1; + let result = prime_as_digits + .iter() + .zip(pattern) + .map(|(old_digit, replace)| if *replace { new_digit } else { *old_digit }) + .map(|d| d as Int) + .rev() + .reduce(|accum, item| { + multiplier *= 10; + accum + multiplier * item + }) + .unwrap(); + debug_assert_eq!(multiplier, 100_000); + result +} + fn get_longest(mut vec: Vec>, print: bool) -> Vec { if vec.is_empty() { panic!("cannot give the longest element of an empty vector") @@ -107,7 +120,7 @@ impl ToNum for Vec { #[cfg(test)] mod test { - use crate::{ToDigits, ToNum}; + use crate::{apply_transformation, ToDigits, ToNum}; #[test] fn test_digits_to_num() { @@ -120,4 +133,15 @@ mod test { let num = 83371; assert_eq!(num.to_digits(), vec![8, 3, 3, 7, 1]); } + + #[test] + fn test_apply_transformation() { + let prime_as_digits = [5, 7, 3, 8, 2, 1]; + let new_digit = 0; + let pattern = [false, true, true, true, false, false]; + assert_eq!( + apply_transformation(&prime_as_digits, new_digit, &pattern), + 500_021 + ); + } }