kernelthread.com

Multiple Languages

The Towers of Hanoi as a program that is valid code in multiple languages (Bourne Again shell, C and Perl). The code can be tried as follows:

bash

% bash hanoi-langN.c 3 move 1 --> 3 move 1 --> 2 move 3 --> 2 move 1 --> 3 move 2 --> 1 move 2 --> 3 move 1 --> 3

C

% gcc -o hanoi hanoi-langN.c % ./hanoi 3 move 1 --> 3 move 1 --> 2 move 3 --> 2 move 1 --> 3 move 2 --> 1 move 2 --> 3 move 1 --> 3

Perl

% perl -x hanoi-langN.c 3 move 1 --> 3 move 1 --> 2 move 3 --> 2 move 1 --> 3 move 2 --> 1 move 2 --> 3 move 1 --> 3

The Code

C=0;/*Towers_Of_Hanoi 2>/dev/null #! /bin/bash H() { case $1 in 0);;*)H $(($1-1)) $2 $4 $3; echo move $2 "-->" $3; H $(($1-1)) $4 $3 $2 ;; esac; } ; case $# in 1)case $(($1>0)) in 1) \ H $1 1 3 2; exit 0 ;;*) echo "$0: illegal value for number of disks"; exit 2;;esac;;*)echo "usage: $0 N";exit 1;;esac; www.kernelthread.com #! perl ($#ARGV==0) or die "usage: $0 N\n"; (($N = int($ARGV[0])) > 0) or die "$0: illegal value for number of disks\n"; H($N, 3, 1, 2);sub H{local ($n,$t,$f,$u)=@_;if($n>0){H($n-1, $u, $f, $t); print "move $f --> $t" . "\n" ; H ( $n - 1 , $t , $u , $f ) ; } } __END__ _*/_(__,_____,___,____){if(__>0){_(__-1,_____,____,___);printf("move" " %d --> %d\n",__,____);_(__-1,____,___,_____);}}main (int _____,char **__){long int ___;if(2!=_____)printf("usage: %s N\n",0[__]),exit(1); ___ = strtol ( 1 [ __ ] , 0 , 0xa ) ; _ ( ___ , 1 , 3 , 2) ;exit(0);}

Download

hanoi-langN.c