Advertisement
ArXen42

Hanoi

May 29th, 2016
339
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 1.71 KB | None | 0 0
  1. Public Module Module1
  2.     Public Sub Main(args As String())
  3.         Console.WriteLine("Enter rings count:")
  4.  
  5.         Dim count As Int32 = -1
  6.         Do Until count > 0
  7.             Try
  8.                 count = Console.ReadLine
  9.                 If (count < 1) Then
  10.                     Console.WriteLine("Number of disks should be greater than zero.")
  11.                 End If
  12.             Catch ex As InvalidCastException
  13.                 Console.WriteLine("Not a number.")
  14.             End Try
  15.         Loop
  16.  
  17.         Hanoi(count)
  18.     End Sub
  19.  
  20.     Private towers As Stack(Of Int32)() = New Stack(Of Int32)(2) {}
  21.  
  22.     Public Sub Hanoi(count As Int32)
  23.         ringsCount = count
  24.         iterationsCount = 0
  25.  
  26.         towers(0) = New Stack(Of Int32)()
  27.         For i As Int32 = 0 To count - 1
  28.             towers(0).Push(count - i)
  29.         Next
  30.  
  31.         towers(1) = New Stack(Of Int32)()
  32.         towers(2) = New Stack(Of Int32)()
  33.  
  34.         Move(count, towers(0), towers(1), towers(2))
  35.         WriteTowers()
  36.     End Sub
  37.  
  38.     Private ringsCount As Int32, iterationsCount As Int32
  39.  
  40.     Private Sub Move(q As Int32, start As Stack(Of Int32), destination As Stack(Of Int32), buffer As Stack(Of Int32))
  41.         If q > 0 Then
  42.             Move(q - 1, start, buffer, destination)
  43.  
  44.             WriteTowers()
  45.             iterationsCount += 1
  46.  
  47.             destination.Push(start.Pop())
  48.  
  49.             Move(q - 1, buffer, destination, start)
  50.         End If
  51.     End Sub
  52.  
  53.     Private Sub WriteTowers()
  54.         Dim strings = New String(ringsCount - 1) {}
  55.  
  56.         For Each tower As Stack(Of Int32) In towers
  57.             Dim i As Int32 = 0
  58.  
  59.             While i < ringsCount - tower.Count
  60.                 strings(i) += ":  "
  61.                 i += 1
  62.             End While
  63.  
  64.             For Each ring As Int32 In tower
  65.                 strings(i) += ring.ToString() + "  "
  66.                 i += 1
  67.             Next
  68.         Next
  69.  
  70.         Console.WriteLine("Шаг № {0}:", iterationsCount)
  71.         For Each str As String In strings
  72.             Console.WriteLine(str)
  73.         Next
  74.         Console.WriteLine()
  75.     End Sub
  76. End Module
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement