Showing posts with label Towers of Hanoi. Show all posts
Showing posts with label Towers of Hanoi. Show all posts

Towers of Hanoi - Programming Environment Lab - JAVA

Program:
import java.io.*;
class han
{
    public void phanoi(int n,int source,int temp,int destn)
    {
        if(n>0)
        {
            phanoi(n-1,source,destn,temp);
            System.out.println("move top disk from "+source+" to "+destn);
            phanoi(n-1,temp,source,destn);
        }

    }
}
class hanoi
{
public static void main (String arg[]) throws IOException
{
    DataInputStream x=new DataInputStream(System.in);
    System.out.print("enter no of disks: ");
    int n=Integer.parseInt(x.readLine());
    han ob=new han();
    ob.phanoi(n,1,2,3);
}
}
Output:
nn@ubuntu:~$ javac hanoi.java
nn@ubuntu:~$ java hanoi
enter no of disks:3
move top disk from 1 to 3
move top disk from 1 to 2
move top disk from 3 to 2
move top disk from 1 to 3
move top disk from 2 to 1
move top disk from 2 to 3
move top disk from 1 to 3
nn@ubuntu:~$

Towers of Hanoi - Programming Environment Lab - LISP

Program:
(defun hanoi(n)
    (dohanoi n 3 1 2)
)

(defun dohanoi(ndisks destination source temp)
    (cond
        ((> ndisks 0) (dohanoi (- ndisks 1) temp source destination)
                (format t "Move the top disk from peg~d to peg~d ~&" source destination)
                (dohanoi (- ndisks 1) destination temp source)
        )
    )
)

Output:
Break 4 [5]> (load 'h.lsp)
;; Loading file h.lsp ...
;; Loaded file h.lsp
T
Break 4 [5]> (hanoi 3)
Move the top disk from peg1 to peg3
Move the top disk from peg1 to peg2
Move the top disk from peg3 to peg2
Move the top disk from peg1 to peg3
Move the top disk from peg2 to peg1
Move the top disk from peg2 to peg3
Move the top disk from peg1 to peg3
NIL
Break 4 [5]>

Towers of Hanoi - C Program

Program:
#include<stdio.h>
//#include<conio.h>
void hanoi(int,int,int,int);
void main()
{
    int no_of_disks, firstpeg=1,secondpeg=2,thirdpeg=3;//clrscr();;
    printf("Enter the no. of disks:");
    scanf("%d",&no_of_disks);
    printf("\n\n Tower of Hanoi problem with %d disks. \n\n", no_of_disks);
    hanoi(no_of_disks,firstpeg,secondpeg,thirdpeg);
    printf("\nSolved...\n");//getch();
}

void hanoi(int n,int peg1,int peg2,int peg3)
{
    if(n!=0)
    {
    hanoi(n-1,peg1,peg3,peg2);
    printf("move disk %d from peg%d to peg%d \n",n,peg1,peg3);
    hanoi(n-1,peg2,peg1,peg3);
    }
}

Output:
nn@linuxmint ~ $ gcc c21.c
nn@linuxmint ~ $ ./a.out
Enter the no. of disks:3


 Tower of Hanoi problem with 3 disks. 

move disk 1 from peg1 to peg3 
move disk 2 from peg1 to peg2 
move disk 1 from peg3 to peg2 
move disk 3 from peg1 to peg3 
move disk 1 from peg2 to peg1 
move disk 2 from peg2 to peg3 
move disk 1 from peg1 to peg3 

Solved...
nn@linuxmint ~ $
Related Posts Plugin for WordPress, Blogger...