Advertisement
Guest User

Untitled

a guest
Mar 20th, 2019
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. // Tower of Hanoi
  2.  
  3. use std::collections::LinkedList;
  4.  
  5. // Inner field stores the disk's width
  6. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
  7. struct Disk(usize);
  8.  
  9. #[derive(Debug, Clone)]
  10. struct Rod(LinkedList<Disk>);
  11.  
  12. impl Rod {
  13. #[inline]
  14. fn new() -> Self {
  15. Rod(LinkedList::new())
  16. }
  17.  
  18. #[inline]
  19. fn len(&self) -> usize {
  20. self.0.len()
  21. }
  22.  
  23. #[inline]
  24. fn is_empty(&self) -> bool {
  25. self.len() == 0
  26. }
  27.  
  28. fn is_descending_order(&self) -> bool {
  29. let mut last = Disk(0);
  30.  
  31. for elem in &self.0 {
  32. if *elem < last {
  33. return false;
  34. }
  35.  
  36. last = *elem;
  37. }
  38.  
  39. true
  40. }
  41.  
  42. #[inline]
  43. fn push(&mut self, d: Disk) {
  44. self.0.push_front(d);
  45. }
  46.  
  47. #[inline]
  48. fn top(&self) -> Option<Disk> {
  49. self.0.front().cloned()
  50. }
  51.  
  52. fn move_to(&mut self, dest: &mut Rod) -> bool {
  53. let x1 = match self.top() {
  54. Some(d) => d,
  55. None => return false,
  56. };
  57.  
  58. let x2 = match dest.top() {
  59. Some(d) => d,
  60. None => {
  61. dest.push(self.0.pop_front().unwrap());
  62. return true;
  63. }
  64. };
  65.  
  66. if x1 < x2 {
  67. dest.push(self.0.pop_front().unwrap());
  68.  
  69. true
  70. } else {
  71. false
  72. }
  73. }
  74.  
  75. #[inline]
  76. fn move_to_either(&mut self, c1: &mut Rod, c2: &mut Rod) -> bool {
  77. self.move_to(c1) || self.move_to(c2)
  78. }
  79. }
  80.  
  81. fn compute_moves(n: usize) -> Vec<String> {
  82. let mut root = Rod::new();
  83. let mut aux = Rod::new();
  84. let mut res = Rod::new();
  85.  
  86. for i in (1..=n).rev() {
  87. // number of disks
  88. root.push(Disk(i));
  89. }
  90.  
  91. let mut alt = 0;
  92.  
  93. while res.len() != n-1 {
  94. match alt {
  95. 0 => {
  96. root.move_to_either(&mut res, &mut aux);
  97. }
  98. 1 => {
  99. aux.move_to_either(&mut res, &mut root);
  100. }
  101. 2 => {
  102. res.move_to_either(&mut aux, &mut root);
  103. }
  104. _ => unreachable!(),
  105. }
  106.  
  107. alt = (dbg!(alt) + 1) % 3;
  108.  
  109. if !res.is_empty() && res.is_descending_order() && res.len() == n-1 {
  110. break;
  111. }
  112. }
  113.  
  114. dbg!((root, aux, res));
  115. Vec::new()
  116. }
  117.  
  118. fn main() {
  119. compute_moves(3);
  120. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement