The Alien, Numbereater and other Programs for Personal Computers Some other computing books from the Macmillan Education Press Beginning BASIC P. E. Gosling Continuing BASIC P. E. Gosling Microprocessors and Microcomputers Eric Huggins A Practical Introduction to Pascal I. R. Wilson and A. M. Addyman The Alien, Numbereater and other Programs for Personal Computers John Race Senior Lecturer, Department of Computer Science Brunei University ©JohnRace 1981 All rights reserved. No part of this publication may be reproduced or transmitted, in any form or by any means, without permission Firstpublishedl981 by THE MACMILLAN PRESS LTD London and Basingstoke Associated companies in Delhi Dublin Hong Kong Johannesburg Lagos Melbourne New York Singapore and Tokyo ISBN 978-0-333-28079-9 ISBN 978-1-349-05175-5 (eBook) DOI 10.1007/978-1-349-05175-5 The paperback edition of this book is sold subject to the condition that it shall not, by way of trade or otherwise, be lent, resold, hired out, or otherwise circulated without the publisher's prior consent in any form of binding or cover other than that in which it is published and without a similar condition including this condition being imposed on the subsequent purchaser Contents Introduction 2 Palindromes 4 Brackets 8 Orbit 13 Pascal's Triangle 25 Superlife 26 Double Density Histograms 39 Spiral Program 45 Remover 50 Prime? 61 Playfair 62 The Alien 67 General Input Program 71 Clear 75 Numbereater 77 Appendix: Amendments to Programs for later PETs with revised ROMs 80 83 Index Introduction From the age of sixteen we can own machines which are physically much more powerful than we are. A Victorian engine driver would have been quite shocked and alarmed at the way young people can now afford to buy, and are allowed to drive, weird conveyances that are more convenient and efficient than his. His engine was far too complex and expensive for amateurs. To some extent, the older generation of computer users look upon the mass market in home computers with the same shocked alarm as the Victorian engine driver would have viewed the moped - even to the extent of denying that the new machine was a real vehicle at all. But now you can buy, and you should buy as soon as you can, a machine - the home computer - which can outperform some of your mental muscles, as the moped outperforms your leg muscles. Of course you are its super ior in many other ways. Unlike it, you can reason by analogy, think laterally, use your imagination. But it can calculate quickly and prec isely, follow specified procedures without deviating by accident or imp ulse, and write and draw tirelessly. A teacher of the old school would certainly call such abilities mental ones, and award high marks to pupils who showed them. What is happening is that, just as we had to learn to accept, and then enjoy, the fact that machines could be strong er than us, so we must now learn how to accept and enjoy the intellect ual powers of computers, which in general happily complement our own. Again, the motorbike overcomes air resistance and friction more spect acularly than we can, but needs us to balance it and direct it. Simil arly a computer will beat us in following defined logical and mathematic al procedures, but needs us to set the problem and define the proced ures. Then, together, we can set off and travel far afield for enjoy ment and profit. This book is for people - students, teachers, or just enthusiasts, at home or in school or college. It is intended as a source of ideas for projects, a series of examples of techniques and applications, and a comfort to those who, like the author, write programs too often that do not work properly, and who then brood over our shortcomings and try to discover more reliable methods for converting our brilliant ideas into sound computer systems. Those who run courses in schools or colleges may find the book useful as a source of worked examples and as recommended background reading, part icularly if the course revolves round the use of BASIC. The programs in the book are mostly in BASIC, and in particular, Commodore PET BASIC. However, although the computer used is the small PET 2001 8K, the pro grams should be transportable with more or less amendment to other BASIC computers such as APPLE, TANDY, SORCEROR, or the British NASCOM, ACORN, or SINCLAIR computers. There are also examples of Assembler and machine code programs for the MCS 6502 microprocessor, used on PET, APPLE 2, and many other systems. If you have a PET with a cassette deck you can buy 1 a cassette containing the programs in this book, by contacting me via Uacmillan Press. There are a number of programs in this book which require additional equ ipment to work: a printer, an interface for a relay to drive an electric light, a second cassette. These may be useful to those who are consider ing extending their,system. BASIC is a language which provokes as much antagonism among professional computer people as the home computer itself. Indeed, it is a language in which it is very easy to write programs that will run, but quite hard to write programs that will run correctly. Since the professionals are rightly concerned about high standards - computers today may kill people in hospitals or aircraft or trains if they fail - they fear that 2 sloppy habits learned from BASIC could become engrained and pernicious. They would prefer the enthusiast to be introduced to computers through a more rigorous language, like PASCAL, in which control structures are safer and programs are rejected by the rules before they try to run on real data. Unfortunately BASIC has become almost a standard language for micros, and variants are used even for process control and business applications ( PLANCOL, DEC BASIC-PLUS). But with self-discipline it is possible to write reasonably clear, fast, safe BASIC programs and - although the author does not always take his own medicine - some tips for overcoming the bad features of BASIC are given in the pages that follow. If you find any mistakes in the programs, do let me know: but I do not accept any responsibility for anyone using a program and coming to grief whether he is an astronaut who falls into the sun by relying on ORBIT or a spy who uses PLAYFAIR and has his transmissions decoded by counter intelligence. My thanks are due to John Watson of Macmillan for encouraging the writ ing of this book, to my son Tom for his program for finding the first sequence of 20 non-primes, which he really did write to do his maths prep in the 3rd form of Abingdon School: to my Brunel student Harminder Ghattaura who wrote a 6502 program to draw double precison lines on the PET screen using Bresenham's algorithm, and to my wife and daughters who had to put up with the noise of a golfball clattering away in the back ground. It was my father's interest in codes and cyphers that prompted the pro gram PLAYFAIR. "Interface box" controlling electric light, Commodore PET 2001 BK, second cassette player, Aculab printer controller, IBM printer. 3 Palindromes Techniques: recursion, string handling, demonstration cheating. Try running the program, and check the results with Figure 1. Adam's famous remark to Eve, Madam I'm Adam, is a palindrome - i.e. it reads the same backwards as forwards, if one ignores the spaces between the words and sticks to upper case. XYZ obviously is not a palindrome. The last trial refers to Ferdinand de Lesseps, whose palindrome is more successful than his attempt to build the Panama canal was. (Napoleon's 'Able was I ere I saw Elba' goes in nicely, spaces and all, since each word matches another of the same length on the other side of 'ere'}. Now look at the program (Figure 2.}. The whole point of this program is to show how you can construct a program to match a formal definition of some data - in this case, a palindrome, which is defined in lines 5 - 6, recursively: that is, the definition makes use of itself. ThiS may seem circular, and it would be, but for the fact that the definition uses itself on a shorter, simpler case - the possible-palindrome with its end characters removed - so that each recursion deals with a shorter string. Secondly the definition includes a terminating condition other than continued use of itself - the 'length 0 or 1' condition, which pro vides an exit and prevents recursion ad infinitum. In computer science recursion is quite useful, for example, to define a 'number': a number is a digit, or a digit concatenated (strung onto} a number. You may also like to see recursion at work in the opposite direction - constructing examples of recursively defined things, instead of checking things against a recursive definition, in 'Brackets'. Back to the program. The sequence of instructions called Palindrome Tester is typical of this type of program. It is responsible for sett ing up a stack of entries for holding the workings at each level of re cursion: R$(} will contain the reply sent up by each lower-level invoc ation of the Tester subroutine to the level above, and A$() will contain the string sent down by one level to the level below for checking. We clearly anticipate having palindrome-candidates of never more than 40 characters in length. Palindrome Tester also has to get the candidate palindrome from the experimenter and place it in A$(0}, the top level. Palindrome Tester uses the Recursive Tester ( GOSUB 1000 } and prints the answer. Recursive Tester simply acts on the rules previously defin ed: if the string it has in its A$(LEVEL} is empty or only one char acter long it can return the answer YES to the routine which called upon it - either Palindrome Tester, if it is at level 0, or a higher level invocation of itself. Otherwise it has to check to see if it can reject the string on the grounds that its first and last characters are not the same ( line 1020 } • Now at line 1030 Recursive Tester has to extract the middle part of the string given to it, using MID$(string,I,J} which returns a substring consisting of the J characters of 'string' starting at the Ith position. It then gets ready to go down by adding one to LEVEL and calls itself. On return from itself, it resets LEVEL and returns YES up\vards if and only if its lower-level examination also said YES. As a matter of fact one could have simplified this program a bit since the descent into recursio~ is a straightforward one-way process - as soon as any level says NO we could leave the program instead of relig iously carrying NO up and up. But in many more complicated examples of recursion, any one level cannot have the authority to decide unilateral ly to terminate the whole process. For example, in chess, recursion can be used to find a player's best move, a.nd each level of the BESTHOVE 4 SEARCHING FOUND PALINDROME LOADING READY. RUN ? MADAMIMADAM MADA MI MADAM ADAMIMADA DAMIMAD AMIMA MIM I YES BREAK IN 60 READY. RUN ? XYZ XYZ NO RUN ? AMANAPLANACANALPANAMA AMANAPLANACANALPANAMA MANAPLANACANALPANAM ANAPLANACANALPANA NAPLANACANALPAN APLANACANALPA PLANACANALP LANACANAL ANACANA NACAN ACA c YES Figure 1. Results of PALINDROMES program 2 REM------------ PALINDROMES---------- 3 REM 5 REM A PALINDROME IS A LETTER-STRING OF LENGTH 0 OR 1, 6 REM OR A PALINDROME WITH THE SAME LETTER ADDED TO EACH END. 8 REM 10 REM-------PALINDROME TESTER--------- 15 REM 20 DIM R$(40) ,A$(40) :REM STACKS 30 INPUT A$(0): REM CANDIDATE P/DROME 40 LEVEL=O: GOSUB 1000 50 PRINT R$(0): REM REPLY YES OR NO 60 STOP 997 REM 998 REM------- RECURSIVE TESTER 999 REM 1000 R$(LEVEL)="YES":REM ASSUME IT IS 1005 PRINT TAB(LEVEL); A$(LEVEL) 1010 IF LEN(A$(LEVEL))=<l THEN 1900 1020 IF LEFT$(A$(LEVEL),l)<>RIGHT$(A$(LEVEL),l) THEN 1890 1030 A$(LEVEL+l)=MID$(A$(LEVEL),2,LEN(A$(LEVEL))-2): REM EXTRACT MIDDLE 1040 LEVEL=LEVEL+l 1050 GOSUB 1000: REM IS MIDDLE A PALINDROME? 1060 LEVEL=LEVEL-1 1070 IF R$(LEVEL+l)="YES" THEN 1900 1890 R$(LEVEL)="NO" 1900 RETURN Figure 2. PALINDROMES program 5