diff --git a/src/bin/1.rs b/src/bin/1.rs index 8a0e89f..8ac4e9f 100644 --- a/src/bin/1.rs +++ b/src/bin/1.rs @@ -1,7 +1,9 @@ -// Problem 1 - Multiples of 3 or 5 +/* +Problem 1 - Multiples of 3 or 5 -// If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. -// Find the sum of all the multiples of 3 or 5 below 1000. +If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. +Find the sum of all the multiples of 3 or 5 below 1000. +*/ use std::collections::HashSet; diff --git a/src/bin/2.rs b/src/bin/2.rs new file mode 100644 index 0000000..26d4cdb --- /dev/null +++ b/src/bin/2.rs @@ -0,0 +1,28 @@ +/* +Problem 2 - Even Fibonacci numbers + +Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: +1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... +By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. +*/ + +fn fibonacci(upper_bound: usize) -> Vec { + // F_0 = 1, F_1 = 2 + let mut sequence = vec![1, 2]; + + // F_n = F_(n - 1) + F_(n - 2) + while sequence[sequence.len() - 1] < upper_bound { + let new_value = sequence[sequence.len() - 1] + sequence[sequence.len() - 2]; + sequence.push(new_value); + } + + return sequence; +} + +fn main() { + let sequence = fibonacci(4000000); + let even = sequence.iter().filter(|n| *n % 2 == 0); + let sum: usize = even.sum(); + + print!("The sum of the first 4000000 even fibonacci numbers is {}", sum); +} diff --git a/src/main.rs b/src/main.rs index 3c72f76..1c13190 100644 --- a/src/main.rs +++ b/src/main.rs @@ -74,29 +74,39 @@ async fn new() -> Result<(), Box> { .collect::>() .join(""); - let mut problem = re.replace_all( - Box::leak( - document - .select(&content_selector) - .next() - .unwrap() - .inner_html() - .into_boxed_str() - ), - " " - ).to_string(); + let mut problem = re + .replace_all( + Box::leak( + document + .select(&content_selector) + .next() + .unwrap() + .inner_html() + .into_boxed_str() + ), + " " + ) + .to_string() + .replace("$$", " "); let file_body = format!( - "// Problem {} - {} + "/* +Problem {} - {} -//{} +{} +*/ fn main() {{ println!(\"Hello World!\"); }}", problem_number, html_escape::decode_html_entities(&mut title).to_string(), - html_escape::decode_html_entities(&mut problem).split("\n").filter(|s| s != &"").collect::>().join("\n//") + html_escape::decode_html_entities(&mut problem) + .split("\n") + .map(|s| s.trim()) + .filter(|s| s != &"") + .collect::>() + .join("\n") ); // Create the file