binary_addition/
binary_addition.rs

1extern crate turing_machine_rs;
2
3use turing_machine_rs::instruction::{Move, State};
4use turing_machine_rs::machines::Classic;
5use turing_machine_rs::program::{Extend, Program};
6use turing_machine_rs::state::Tape;
7use turing_machine_rs::TuringMachine;
8
9// For more comfortable coding, use Result<(), String>:
10// `?` postfix symbol is better then `.unwrap()` postfix method call.
11fn main() -> Result<(), String> {
12    let mut program = Program::new(vec![' ', '0', '1', '+'], State(8));
13    program.extend([
14        // Sub 1, also init zero check
15        (1, ' ', 0, ' ', Move::None),
16        (1, '0', 1, '0', Move::Left),
17        (1, '1', 2, '0', Move::Right),
18        (1, '+', 6, '+', Move::Right),
19        // Subs part
20        (2, ' ', 3, ' ', Move::Left),
21        (2, '0', 2, '1', Move::Right),
22        // 2, '1' -> Impl
23        // 2, '+' -> Err
24        //
25        // Find + on left
26        // 3, ' ' -> Err
27        (3, '0', 3, '0', Move::Left),
28        (3, '1', 3, '1', Move::Left),
29        (3, '+', 4, '+', Move::Left),
30        // Add 1
31        (4, ' ', 5, '1', Move::Right),
32        (4, '0', 5, '1', Move::Right),
33        (4, '1', 4, '0', Move::Left),
34        // 4, '+' -> Err
35        //
36        // Find + on rigth
37        // 5, ' ' -> Imp
38        (5, '0', 5, '0', Move::Right),
39        (5, '1', 5, '1', Move::Right),
40        (5, '+', 6, '+', Move::Right),
41        // Zero check
42        (6, ' ', 8, ' ', Move::Left),
43        (6, '0', 6, '0', Move::Right),
44        (6, '1', 7, '1', Move::Right),
45        // 6, '+' -> Err
46        //
47        // Find last num
48        (7, ' ', 1, ' ', Move::Left),
49        (7, '0', 7, '0', Move::Right),
50        (7, '1', 7, '1', Move::Right),
51        // 7, '+' -> Err
52        //
53        // Clear + and after
54        // 8, ' ' - Imp
55        (8, '0', 8, ' ', Move::Left),
56        // 8, '1' - Imp
57        (8, '+', 0, ' ', Move::Right),
58    ])?;
59    let machine = Classic::new(program, ' ')?;
60
61    // Change and try to run this example!
62    let lhs = "10101";
63    let rhs = "111";
64    // -----------------------------------
65    let tape = Tape::from(format!("{}+{}", lhs, rhs));
66
67    let res = machine.translate_std(tape)?;
68    println!("{} + {} = {}", lhs, rhs, String::from_iter(res.as_vec()));
69
70    Ok(())
71}