Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Public Module Module1
- Public Sub Main(args As String())
- Console.WriteLine("Enter rings count:")
- Dim count As Int32 = -1
- Do Until count > 0
- Try
- count = Console.ReadLine
- If (count < 1) Then
- Console.WriteLine("Number of disks should be greater than zero.")
- End If
- Catch ex As InvalidCastException
- Console.WriteLine("Not a number.")
- End Try
- Loop
- Hanoi(count)
- End Sub
- Private towers As Stack(Of Int32)() = New Stack(Of Int32)(2) {}
- Public Sub Hanoi(count As Int32)
- ringsCount = count
- iterationsCount = 0
- towers(0) = New Stack(Of Int32)()
- For i As Int32 = 0 To count - 1
- towers(0).Push(count - i)
- Next
- towers(1) = New Stack(Of Int32)()
- towers(2) = New Stack(Of Int32)()
- Move(count, towers(0), towers(1), towers(2))
- WriteTowers()
- End Sub
- Private ringsCount As Int32, iterationsCount As Int32
- Private Sub Move(q As Int32, start As Stack(Of Int32), destination As Stack(Of Int32), buffer As Stack(Of Int32))
- If q > 0 Then
- Move(q - 1, start, buffer, destination)
- WriteTowers()
- iterationsCount += 1
- destination.Push(start.Pop())
- Move(q - 1, buffer, destination, start)
- End If
- End Sub
- Private Sub WriteTowers()
- Dim strings = New String(ringsCount - 1) {}
- For Each tower As Stack(Of Int32) In towers
- Dim i As Int32 = 0
- While i < ringsCount - tower.Count
- strings(i) += ": "
- i += 1
- End While
- For Each ring As Int32 In tower
- strings(i) += ring.ToString() + " "
- i += 1
- Next
- Next
- Console.WriteLine("Шаг № {0}:", iterationsCount)
- For Each str As String In strings
- Console.WriteLine(str)
- Next
- Console.WriteLine()
- End Sub
- End Module
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement