From 14b400accb768cb05fcb450f1ae406ee58b546bf Mon Sep 17 00:00:00 2001 From: Coin de Gamma Date: Tue, 7 Mar 2023 09:08:59 +0000 Subject: [PATCH] 014 ok --- 014/main.rs | 36 +++++++++++++++++++++--------------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/014/main.rs b/014/main.rs index a0cba3d..c7883a9 100644 --- a/014/main.rs +++ b/014/main.rs @@ -1,38 +1,44 @@ -type CZS = Vec>; +use std::collections::HashMap; +type CZS = HashMap; struct Collatz { czs: CZS } impl Collatz { pub fn new() -> Collatz { - let cl0 = Some(0); // for indexing - let cl1 = Some(1); - Collatz { czs: vec![cl0, cl1] } + let mut res = Collatz { czs: HashMap::new() }; + res.czs.insert(1, 1); + res } - pub fn compute(&mut self, n: usize) -> u32 { - match self.ensure_get(n) { - Some(cl) => cl, + pub fn compute(&mut self, n: u64) -> u64 { + match self.czs.get(&n) { + Some(cl) => *cl, None => { //println!("compute {}", n); - let cl_prev = if n % 2 == 0 { + let cl_prev = if n % 2 == 0 { self.compute(n / 2) } else { self.compute(3 * n + 1) }; - self.czs[n] = Some(cl_prev + 1); + self.czs.insert(n, cl_prev + 1); cl_prev + 1 } } } - pub fn ensure_get(&mut self, i: usize) -> Option { - while self.czs.len() <= i { self.czs.push(None); } - self.czs[i] - } } fn main() { let mut collatz = Collatz::new(); - for k in 0..100000usize { + let n = 1_000_000u64; + let mut best_cl = 1; + let mut best_n = 1; + + for k in (2..=n).step_by(1) { let clk = collatz.compute(k); - println!("{}: {}", k, clk); + if clk > best_cl { + best_cl = clk; + best_n = k; + } + //println!("{}: {}", k, clk); } + println!("{} -> {}", best_n, best_cl); }