16 December 2014

More Rust!

Yet another Rust meetup!

So keeping in the spirit of these posts, I will write a train of thought as I code!

Goal: Project Eular

Starting with problem one.

Find the sum of all the multiples of 3 or 5 below 1000.

This is going to be super similar to the FizzBuzz before. Find the multiples and add them to an accumulator of some sort.

fn pe1 (i :int) {
    let mut acc = 0i;
    for i in range(0, i) {
	if i % 3 == 0 {
	    acc += i
	}
	if i % 5 == 0 {
	    acc += i
	}
    }
    println!("{}", acc);
}

fn main() {
    pe1(10);
    pe1(1000);
}

Hrmmmm. This is failing. :(

     Running `target/hello_world`
23
266333

First I thought it was an off by one error but it is not. Oh I amm dumb!

It adding i twice in the case of 15. Bring in our friend: the humble else

Done!

fn pe1 (i :int) {
    let mut acc = 0i;
    for i in range(0, i) {
	if i % 3 == 0 {
	    acc += i
	} else if i % 5 == 0 {
	    acc += i
	}
    }
    println!("{}", acc);
}

fn main() {
    pe1(1000);
    pe1(10);
}


$ cargo run
   Compiling hello_world v0.0.1 (file:///home/tim/rust-demo/hello_world)
/home/tim/rust-demo/hello_world/src/main.rs:1:1: 13:2 warning: function is never used: `fizzbuzz`, #[warn(dead_code)] on by default
/home/tim/rust-demo/hello_world/src/main.rs:1 fn fizzbuzz() {
/home/tim/rust-demo/hello_world/src/main.rs:2     for i in range(0, 100i) {
/home/tim/rust-demo/hello_world/src/main.rs:3         if i % 3 == 0 {
/home/tim/rust-demo/hello_world/src/main.rs:4             print!("Fizz");
/home/tim/rust-demo/hello_world/src/main.rs:5         }
/home/tim/rust-demo/hello_world/src/main.rs:6         if i % 5 == 0 {
					      ...
     Running `target/hello_world`
233168
23

Woot!woot!