Skip to content

Instantly share code, notes, and snippets.

@mibmo
Last active October 25, 2023 13:53
Show Gist options
  • Save mibmo/d459dfb69aade1db24cd0be07bcb3afd to your computer and use it in GitHub Desktop.
Save mibmo/d459dfb69aade1db24cd0be07bcb3afd to your computer and use it in GitHub Desktop.
Rust recursive towers of hanoi

A simple Towers of Hanoi solver.

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