home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.programming
- Path: sparky!uunet!gumby!wupost!uwm.edu!csd4.csd.uwm.edu!markh
- From: markh@csd4.csd.uwm.edu (Hunk)
- Subject: Re: Teaching the basics
- Message-ID: <1992Aug19.154830.11787@uwm.edu>
- Sender: news@uwm.edu (USENET News System)
- Organization: Computing Services Division, University of Wisconsin - Milwaukee
- References: <1992Aug17.123916.14815@husc13.harvard.edu> <14066@goanna.cs.rmit.oz.au>
- Date: Wed, 19 Aug 1992 15:48:30 GMT
- Lines: 47
-
- In article <14066@goanna.cs.rmit.oz.au> ok@goanna.cs.rmit.oz.au (Richard A. O'Keefe) writes:
- >If you don't know recursion, you don't know programming. It is one of the
- >simpler concepts in computing. (Much simpler than mutable variables, IMHO.)
-
- I think recursion is a farce. And just to rub it in, here's the Towers of
- Hanoi (up to N = 31, I'm assuming long integers are 32 bits) without it (in C):
-
- #include <stdio.h>
-
- /* Move a stack of N objects from tower A to C, using B */
- void Hanoi(int N, char A, char B, char C) {
- unsigned long X = 0; char D;
- HANOI:
- if (N > 0) {
- D = B, B = C, C = D, N--;
- X = 2*X + 2; goto HANOI; X2: X = (X - 1)/2;
- N++, D = B, B = C, C = D;
- printf("Move %d from %c to %c.\n", N, A, C);
- D = A, A = B, B = D, N--;
- X = 2*X + 1; goto HANOI; X1: X = (X - 1)/2;
- N++, D = A, A = B, B = D;
- }
- if (X&1) goto X1;
- if (X > 0) goto X2;
- }
-
- main() { Hanoi(5, 'a', 'b', 'c'); }
-
- or with the recursion scars removed, and algebraic cancellations carried out,
- this:
-
- #include <stdio.h>
-
- /* Move a stack of N objects from tower A to C, using B */
- void Hanoi(int N, char A, char B, char C) {
- unsigned long X = 0; char D;
- while (1) {
- if (N&1) D = B, B = C, C = D;
- for (; N > 0; N--) X = (X + 1) << 1;
- for (; X&1; X >>= 1, N++) D = A, A = B, B = D;
- if (X == 0) break;
- printf("Move %d from %c to %c.\n", N + 1, A, B);
- D = C, C = B, B = A, A = D, X--;
- }
- }
-
- main() { Hanoi(5, 'a', 'b', 'c'); }
-