diff --git a/insert_digit_anywhere_primes b/insert_digit_anywhere_primes new file mode 100755 index 0000000..e6ddc54 Binary files /dev/null and b/insert_digit_anywhere_primes differ diff --git a/insert_digit_anywhere_primes.py b/insert_digit_anywhere_primes.py index 1a4cba3..7cf8cf3 100644 --- a/insert_digit_anywhere_primes.py +++ b/insert_digit_anywhere_primes.py @@ -69,10 +69,11 @@ def step(x): def main(): tree = Tree(0, [2, 3, 5, 7]) - for i in range(20): + for i in range(5): print(tree.longest_path()) tree.step() print(tree.longest_path()) + print(tree) if __name__ == '__main__': diff --git a/insert_digit_anywhere_primes.rs b/insert_digit_anywhere_primes.rs new file mode 100644 index 0000000..5318d19 --- /dev/null +++ b/insert_digit_anywhere_primes.rs @@ -0,0 +1,86 @@ +use std::collections::HashMap; + +#[derive(Debug)] +struct Tree { + value: u64, + children: Vec, +} + +impl Tree { + fn new(value: u64, children: Vec) -> Tree { + let mut tree_children = Vec::with_capacity(children.len()); + for child in children { + tree_children.push(Tree::new(child, Vec::new())); + } + Tree { + value, + children: tree_children, + } + } + + fn step(&mut self, primes: &mut HashMap) { + if self.children.is_empty() { + let str_x = self.value.to_string(); + for i in 0..str_x.len() + 1 { + for d in 0..10 { + let temp = format!("{}{}{}", &str_x[..i], d.to_string(), &str_x[i..]).parse().unwrap(); + if !(i == 0 && d == 0) { + if is_prime(temp, primes) { + self.children.push(Tree::new(temp, Vec::new())); + } + } + } + } + return; + } + for child in &mut self.children { + child.step(primes); + } + } + + fn longest_path(&self) -> Vec { + if self.children.is_empty() { + return vec![self.value]; + } + let mut max_path = vec![]; + let mut max_length = 0; + for child in &self.children { + let temp = child.longest_path(); + if temp.len() > max_length { + max_length = temp.len(); + max_path = temp; + } + } + let mut retval = vec![self.value]; + retval.append(&mut max_path); + return retval; + } +} + +fn is_prime(x: u64, primes: &mut HashMap) -> bool { + let is_prime = primes.get(&x); + match is_prime { + Some(val) => return *val, + None => { + let mut i = 2; + while i * i <= x { + if x % i == 0 { + primes.insert(x, false); + return false; + } + i += 1; + } + primes.insert(x, true); + return true; + }, + } +} + +fn main() { + let mut tree = Tree::new(0, vec![2, 3, 5, 7]); + let mut primes: HashMap = HashMap::new(); + for _ in 0..10 { + tree.step(&mut primes); + println!("{:?}", tree.longest_path()); + } +}