Wanna know a cool trick? You can take the n = out of the ifs. That makes the code a bit easier to read in the fact that you know right away that the expression always just mutates n. Here would be my version:
fn collatz(mut n: u32) -> Vec<u32> {
let mut result: Vec<u32> = vec![n];
while n > 1 {
n = if n % 2 == 0 { n/2 } else { 3 * n + 1 };
result.push(n)
}
result
}
fn main() {
for i in 1..6 {
println!("{:?}", collatz(i))
}
println!("hiiii")
}
View all comments
Show parent comment
3
u/Will_i_read May 17 '22 edited May 17 '22
Wanna know a cool trick? You can take the
n =out of the ifs. That makes the code a bit easier to read in the fact that you know right away that the expression always just mutates n. Here would be my version: