A simple Towers of Hanoi solver.
Last active
October 25, 2023 13:53
-
-
Save mibmo/d459dfb69aade1db24cd0be07bcb3afd to your computer and use it in GitHub Desktop.
Rust recursive towers of hanoi
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let solution = hanoi(3, 'A', 'B', 'C'); | |
for (i, hanoi_move) in solution.iter().enumerate().map(|(i, m)| (i + 1, m)) { | |
eprintln!("{i}: {hanoi_move:?}"); | |
} | |
} | |
#[derive(Debug)] | |
struct Move { | |
from: Peg, | |
to: Peg, | |
} | |
type Peg = char; | |
fn hanoi(height: u32, start: Peg, intermediary: Peg, end: Peg) -> Vec<Move> { | |
match height { | |
1 => vec![Move { from: start, to: end }], | |
2 => vec![ | |
Move { from: start, to: intermediary }, | |
Move { from: start, to: end }, | |
Move { from: intermediary, to: end }, | |
], | |
_ => { | |
let mut moves = Vec::new(); | |
moves.append(&mut hanoi(height - 1, start, end, intermediary)); | |
moves.push(Move { from: start, to: end }); | |
moves.append(&mut hanoi(height - 1, intermediary, start, end)); | |
moves | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment