This blog is my notebook(Python3, LinuxMint, Rust-lang, Nim-lang etc...)
Sunday, March 25, 2018

The tower of hanoi by Rust-lang

Recursive function


The tower of hanoi algorithm is practice for recursive function. Let's try!
This program is hanoi algorithm. But I must change main function's n, if I want to know the movement of 5 disks. It is troublesome.

fn hanoi(n: i32, a: &str, b: &str, c: &str) {
    if n > 0 {
        hanoi(n - 1, a, c, b);
        println!("{} => {}", a, c);
        hanoi(n - 1, b, a, c);
    }
}

fn main() {
    hanoi(3, "A", "B", "C");
}

$cargo run
   Compiling pg3 v0.1.0 (file:///home/masahiko/rust_dev/pg3)
    Finished dev [unoptimized + debuginfo] target(s) in 1.2 secs
     Running `target/debug/pg3`
A => C
A => B
C => B
A => C
B => A
B => C
A => C

Therefore I have changed it a little.

use std::env;

fn hanoi(n: i32, a: &str, b: &str, c: &str) {
    if n > 0 {
        hanoi(n - 1, a, c, b);
        println!("{} => {}", a, c);
        hanoi(n - 1, b, a, c);
    }
}

fn main() {
    let mut x = env::args();
    let y = x.nth(1).unwrap();
    let z = i32::from_str_radix(&y, 10).unwrap();
    hanoi(z, "A", "B", "C");
    let num: f64 = 2.0;
    println!("Move: {}", (num.powi(z) - 1.0f64));
}
env::args() is similar to sys.argv of Python. x is command-line argument. x.nth(1) is sys.argv[1] of Python. i32::from_str_radix() expresses the number of the string as a specified radix. For example..

let x = "10";
    
// 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,10
println!("{}", i32::from_str_radix(x, 16).unwrap()); // 16
    
// 0,1,2,3,4,5,6,7,10
println!("{}", i32::from_str_radix(x, 8).unwrap()); // 8
    
// 0,1,10
println!("{}", i32::from_str_radix(x, 2).unwrap()); // 2

If the radix is 10, that means that you can use the number of the string as it is.
Let's run it!

$cargo run 3
   Compiling pg3 v0.1.0 (file:///home/masahiko/rust_dev/pg3)
    Finished dev [unoptimized + debuginfo] target(s) in 1.2 secs
     Running `target/debug/pg3 3`
A => C
A => B
C => B
A => C
B => A
B => C
A => C
Move: 7

I consider that I need to study error handling a little more :)

Additional note

Oct 15, I created new library of the tower of hanoi. Please check my repo.

No comments:

Post a Comment