# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     name: python3
# ---

# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/r-chaudhary/Artificial-Intelligent-Repo/blob/master/ToweOfHanoi.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>

# + [markdown] id="Uc19D5VjNySS" colab_type="text"
# # Tower of Hanoi
#
#
# ---
#
#

# + [markdown] id="X4slCpaTN1MC" colab_type="text"
# The Tower of Hanoi is a mathematical game or puzzle. It consists of three rods and a number of disks of different sizes, which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape. 
#
#
# ---
#
#

# + [markdown] id="QjhuIWBWOOHp" colab_type="text"
# The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
#
# 1.   Only one disk can be moved at a time.
# 2.   Each move consists of taking the upper disk from one of the stacks a placing it on top of another stack or on an empty rod.
# 3.   No larger disk may be placed on top of a smaller disk.
#
# With 3 disks, the puzzle can be solved in 7 moves. The minimal number of moves required to solve a Tower of Hanoi puzzle is 2n − 1, where n is the number of disks.
#
# ---
#
#

# + [markdown] id="23LTCu3LOfBB" colab_type="text"
# ## Animation
# <br>
#
# ![Towerof hanoi](https://drive.google.com/uc?export=view&id=1wXhApssCkGXDXH9B7zvolAQ02YXrXCv2)
#
#
# ---
#
# Source : [Wikipedia](https://en.wikipedia.org/wiki/Tower_of_Hanoi)
#
#

# + [markdown] id="UL7IPsILP__O" colab_type="text"
# ## Code

# + id="K-FVdYvvMrXT" colab_type="code" colab={}
import matplotlib.pyplot as plt


# + id="bl_9lEOG5y0J" colab_type="code" colab={}
class Tower:
    def __init__(self, disks):
        self.width = (len(disks)*5*3 + 10)/3
        self.height = len(disks)*5 + 5
        self.tower = {
                        "T1":{  
                                "coords":[0, self.height], 
                                "stack": [disks[i] for i in range(len(disks)-1,-1,-1) ]
                            }, 
                        "T2": { 
                                "coords":[self.width, self.height],
                                "stack": []
                            }, 
                        "T3": { 
                                "coords":[self.width*2, self.height], 
                                "stack": []
                            }
                      }
        


# + id="F0AkvxKrkGAS" colab_type="code" colab={}
class Disk:
    def __init__(self, length, color="blue"):
        self.name = str(length)
        self.height = 5
        self.width = length * 5
        self.xpos = 0
        self.ypos = 0
        self.color = color
    
    def __str__(self):
        return self.name



# + id="iukWpRruGYbl" colab_type="code" colab={}
class TowerOfHanoi:
    def __init__(self, ndisks):
        self.ndisks = ndisks
        self.steps = 0
        self.disks = []
        for i in range(1,ndisks+1):
            self.disks.append(Disk(i))
        self.tower = Tower(self.disks)
        self.compute()
        print("Total Steps taken ",self.steps)
        
        
    def compute(self):
        self.draw(self.tower.tower)
        def tower_of_hanoi(disks, source, target, middle):
            if disks > 0:
                tower_of_hanoi(disks-1,source,middle,target)

                print("Move Disk [ {:<3} ] From [ {:<3} ] To [ {:<3} ]".format(disks,"T"+str(source),"T"+str(target)))   
                disk = self.tower.tower["T"+str(source)]["stack"].pop()
                self.tower.tower["T"+str(target)]["stack"].append(disk)
                self.draw(self.tower.tower)
                self.steps += 1
                tower_of_hanoi(disks-1,middle,target,source)

        tower_of_hanoi(self.ndisks,1,3,2)


    def draw(self, state):
        plt.axes()
        for i in state:
            rectangle = plt.Rectangle((self.tower.tower[i]["coords"][0],0), self.tower.width, 5, fc='black',ec="red")
            plt.gca().add_patch(rectangle)
            y = 6
            for j in state[i]["stack"]:
                x = (self.tower.width - j.width) / 2 + self.tower.tower[i]["coords"][0]
                
                height = j.height
                width = j.width
                
                rectangle = plt.Rectangle((x,y), width, height, fc='blue',ec="red")
                plt.gca().add_patch(rectangle)

                y += j.height + 0.5
        plt.axis('scaled')
        plt.xticks([])
        plt.yticks([])
        plt.show()

# + [markdown] id="fQY-Dy-cQCHV" colab_type="text"
# ## Output

# + id="ru6IkL3ME4gw" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="9ba19d0f-8239-4c5d-f5dd-6edf3d757262"
TowerOfHanoi(5)

# + id="6j5wJTDTGMSg" colab_type="code" colab={}


StarcoderdataJupyterScriptsDedupFiltered