Home
Locate
CS 101
CS 496
Login
Tutors
Marks
About
Send
Close
Add comments:
(status displays here)
Got it!
This site uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.
nbsp; Note: This appears on each machine/browser from which this site is accessed.
Towers of Hanoi in various languages
by RS
admin@ycp.powersoftwo.org
c
go
java
js
lua
py
vbs
rkt
scm
pro
1. Towers of Hanoi in various languages
2. C code
Here is the C code.
#include <stdio.h> void move(int n1, char *a1, char *b1, char *c1) { if (n1 != 0) { move(n1-1,a1,c1,b1); printf("move %d from %s to %s\n",n1,a1,b1); move(n1-1,c1,b1,a1); } } int main() { move(3,"a","b","c"); return 0; }
3. C output
Here is the output of the C code.
move 1 from a to b move 2 from a to c move 1 from b to c move 3 from a to b move 1 from c to a move 2 from c to b move 1 from a to b
4. Java code
Here is the Java code.
public class toh2_01 { public void move(int n1, String a1, String b1, String c1) { if (n1 != 0) { move(n1-1,a1,c1,b1); System.out.print(String.format("move %d from %s to %s\n",n1,a1,b1)); move(n1-1,c1,b1,a1); } } public toh2_01() { move(3,"a","b","c"); } public static void main(String [] args) { new toh2_01(); } }
5. Java output
Here is the output of the Java code.
move 1 from a to b move 2 from a to c move 1 from b to c move 3 from a to b move 1 from c to a move 2 from c to b move 1 from a to b
6. Python code
Here is the Python code.
def move(n1, a1, b1, c1): if n1 != 0: move(n1-1,a1,c1,b1) print("move {0:d} from {1:s} to {2:s}".format(n1,a1,b1)) move(n1-1,c1,b1,a1) move(3,"a","b","c")
7. Python output
Here is the output of the Python code.
move 1 from a to b move 2 from a to c move 1 from b to c move 3 from a to b move 1 from c to a move 2 from c to b move 1 from a to b
8. End of page
by RS
admin@ycp.powersoftwo.org