Progromming Recursive in BASIC

advertisement
,
.
Recursive
Progromming
in BASIC
Hlrb.n L. D.rshom
_ '1;:n;i
;1:::
call. This return to eachof thc pte"io;;tt'"'t.i
t\ ecursioncan be a valuabletool on microcomputers out a recudve
i,
levelsincrcmentst by one. On the finai retum' I lhould
il shouldbe in everyPIo'
K usingBASIC.For lhis reason.
process
wascarieJ out corEcdv .ThB: -.-.{ei!
if
rhe
21N-l
equal
,
repertoire.
Brammer's
if this proqlamrunslor a 8i!en valueol N tnrsv€ ron oI ==:
callt. Msny wrsionsof EASIC -T,.
BAslc'all;ws N.l recursive
lvhat is recutsion?
ol suchcallspGsible.
nun)be'
on
th€
no
tinril
.'jvirtually
set
ln
of
irself
Anvlhinr is recursiveif it is definedin terfte
lflheBAslcisno!recursivelo|heaPpropriat.l.vrIfor
on
ilself_
calls
subroutine
a recursive
rrocranminr.
'
somevalueol N, it usuallyrerpondswirh tomc tyPc-of
*:
bon\ coifrrserecursionwith iteration'sjnceboth often
ratherthan alrivingat strlement 170.
nressag"
dingnostic
aproce'
is
clear:
ploblem.
distinction
The
the
same
solve
can
begunand
is performed,
durais iterativeif the sameprocess
subroutines
in
the mid_ Writingrecursive
if.
h lecursive
compleledrepealedtyia
PloceJute
allow
doe3
BASIC
lf vouhavefoundthatyourcompuler's
dle of its execution,it calh upon itself.Thereforea l€cur'
p.oblcm
wilh
the
you
faced
now
iecunive
subroutines, are
siveprocedurebegnt anotherexecu(ionofitselfbeforelhe
them.Thenfollow lhis genefaloutlineof recun
writing
of
more
has
r
Such
finished.
is
Procedure
orisinalexecution
an
sivesubroutinein BASIC:
tha-none executionin progres!at a Siventime, whercas
Iterativ€proccdu!€neverhasmore than ons in Progre$'
l. Ifthe first call,inilializcthe stackpoint€r.
2. If terminationcondition,computercsult,decremrnt
for
tecuNion
stackPoi er, relurn..
Testing
In
3. Do comPutation.
Nor every languaieimplemenlalionPermiis.ecu6ion.
valuesin stack
cill
a
4.
Saven€cessary
to
BASIC.ricursionis onty possibleif it is Permissible
slack
the
oti'
5,
IncremenL
the
ability
of
Pointetsubrouiinefrom itself and still retxin
lhis
subroutine.
your
clll
Recursively
p.oPel
test
5.
To
to
the
ioint.
cinalexecutionto returd
-8ASIC
?, Reslorcsavedvaiuesfrom thestack
capabilityus! th€ followingprogmm:
for recursion
8, Do aoy remailingcomputatlon.
tO REM TEST FOR THE ABILIry OF THE BASICTO
stackPoinler'
9. Decrement
PERFOR]!'RECURSION
10. Relurn.
20 N-l
30 t=0
clll I subroulifleflom itself; the
WlLenvou reeursivelv
deslloythevarirblesof lhe
40 GosuB100
eteculion
varirblesin rfiecriled
the oriSinil
50 IF I<> 2*N-ITHENI7O
To pr€rerve
executior'
crlling
in
lhc
samenu'l]e
N-l;"TIMES'"
variable
60 PRINT'RECURSIVE";
ulues of thesevariables,srve in a dimensioned
you needto reoalllater.Sup_
(cal:eda stnck)thosevariables
70 N=Nrl
80 GOTO30
has threevarjables- X, Y and Z ooscvoru subr'ortirre
100 I=l+l
itrat ii wisbesto ssvefor recall,vhen it tetulnsfrom a re'
I10 IF I<N THENI3O
cursivecall. The tornrat of th€ stacksfor thesevariables,
vadablesof the
I:O RETURN
wtrichare inlroducedby tlrreesubscripted
100
representation:
cosuB
the
tollowing
130
samenanles,uses
140 lF l>2rN-l THEN170
X(l) X front execution
150I =I+l
Y(l) Y fromcxec tio.r
I60 RETURIi
Z(l) Z fron execulioil
'NOT RECURSIVE";
"
N-l ;"TINIES
l70 PRINT
X(2) X ionr executionl
I80 END
Y(2) Y from execution2
I
execution:
z
from
Z(2)
nre
one
I
bv
incre'nenls
l0O
of
sub.ouline
evervcall
I
Nrh crll re:ultsio tle setlingof I lo N anda relurnwith-
i
I
i.L.
To l:eeptrackofthe Positionin the stackwherethe cur'
' rent exicution savesits values,usea pointer.Everyrecur'
this pointerby one.Uke'l/ise,eachre'
sivecall incr€ment3
the
turn decremeots pointerby one.
plocedurejustourlinedshowsonly
The generalrecursive
stePs3 to 8
ln general,
call in the subroutine.
one recursive
mry be rep€atedseveraltimesbeforercturningto steps9
and 10.
An example: calculating N!
Let's take a recursiv€subroutbe and follow th€se steps.
Let's use the classicexamPleof factorialtecursionUn_
is not fte
recursion
itt alsoa problembecause
fortunaaely,
famil'
the
most
lt
b
however,
a
solution;
wav
io
obtain
best
sowhy bleaktrcdidon?
iar cnd;imptestofal examPles.
Tlre conrmondelinition of N factorial(N:) is itcrative
+2+t for N = I'
and giver by: N' = N{N-I)*(N.2)' . ..
=
this rccursive
(where
there
is
also
l).
But
0!
2, . . .
= 1,2' . . .
=
for
N
N*(Nt)!
N!
of
N
factori.l:
detinilion
(wh€re 0! = l). Notice that th€ factoriel is defined in
termsbf itself,but with one€scapeclaus€which occursat
O!. The recuniveform of a subroutineto computeN! is
cxemplifiedby thissamplecallingProglarn:
REM THIS SUBROUTINECOMPUTESN FAC.
960
AND
TORIAL RECURSIVELY
g7O
REM STORESTHE RESULTIN F. THE FIRST
CALL lS TO 990.
CALTSARE TO IOOO.
980
REM.SUBSEQUENT
990
S= I
to00 IF N<>0 THEN1040
l0l0 F: I
1020 S = S.1
IO3O RETURN
l0a0 N(s)= N
1050
1060
1070
1080
1090
ll00
I I IO
S = S+l
N = Nl
00suB 1000
N = N(S)
F = N*F
S=S-l
RETURN
Of course,the iterativeve.sionof the fa€to.id subroutine is much sinpler and exe€utesmuch faster.Thjs is aJril_
erativeversionofa sampleccllingprogram:
TO COM.
REM ITERATIVE SUBROUTINE
PUTEN FACTORIAL
REMANDSTOREIT IN F.
980
1000 F = I
l0l0 IF N<= I THEN1050
1020 F O R I = 2 T O N
F=Fjl
1030
lM0 NEXTI
1050 RETURN
910
REM CALLINGPROCRAM
FACTORIALS
10 COMPUTE
ITERATIVELY
20 INPUTN
1000
30 GOSUB
40 PRINTF
50 coro 20
l0
FibonacciSeries
Computing
the Fibonacci
Another€xampleof recursio is calculating
of nunbers.The Nth numberin the Fibonaccisesequenc€
quence,F(N),is definedin iermsofits two Predecessors.
F(0) = 0
F(l) = I
F(N)= F(N-l)+ F(N-2)ro. N + 2, 3'...
The BASICversionofthis alSorithmnndits callingprogram
91O
980 .
REM SUDROUTINE990 CALCULATESTHE
NTH FIBONACCINUMBER
REM RICURSIVELY
AND RETURNSIT IN F.
990 s= |
1000 IFN=0THEN1020
IOIb IF N <> l THENIO5O
1020 F=N
1030 S = S-1
IO4O RETURN
1050 N(s)= N
FOR
REPROGRAM
CALLTNG
SAMPLE
IO REM
1060 S= S+1
CURSIVE
FACTORIALS
1070 N = N.l
20 DrMN (l0o)
1080 cosuB 1000
30 INPUTN
1090 N = N(S)
40 GOSUF
990
I100 F(S)=F
50 PRINTF
lll0 S=S+l
60 GOTO30
ll20 N-N-2
I130 cosuB 1000
to stepI in
In lhisprognm,shlement990 conesPond!
llao N=N(s)
Sutenents1000'1030
dgorith givenearlier.
thc general
50 F=F(S)+F
is
condition
to step2, in whichthetermination
correspond
1
1
6 0 S =S - l
to step I I7O
correspond
in thisprogram
N - 0. No computalions
RI]TURN
colrespond
steps
algorithn.Theremaioing
3 of thegeneral
asfollows:
to statements
IO REMCALLiNGPROGRAM
NOS.
FIBONACCI
TO COMPUTE
RECURSIVELY
Slep..tt .
20 DrMN(50),F(50)
30 INPUTN
990
40 GOSUB
6
,|
50 PRINTF
60 GOTO30
8
i :,
9
l0
a
asjnthecaseofthe factorial,i telationSives
Again,just
lo thisproblem.
moreeffici€ntsolution
,ULYl9t8oOigiLllrc.ign 2l
1020 T{FtS))= T(F(S))+ |
1030 PRrNi'MOVE-: E(S);"TO'i F(S)
1040 coTo 1190
1050 G = 6 - ( E ( S ) + F ( s ) )
1060 s = s + l
1070 D(s)= D(s'l)- I
=c
1080 F(s)
1030
Q=F
=E(s-r
1090 E(S)
)
I O.tO
1OOO
GOSUB
1
1
0
0
P=Q
t050
I
l l l 0 r(E(s)- r(E(s))1060 NEXTI
T(FrS))= T(F(S))+ I
I
l
]
0
1070 RETURn*
I I30 PRINT'MOVE-lE(S);"TO": F(9
ITERATIVELY
TO
PROGR'JI
CALLING
REM
IO
I I40 s = s l I
NOS.
FIBONACCI
COMPUTE
| 150 D(S)=D(91)"1
:o INPUTN
I 160 E(s)=6.(E(s-l)+F(S-l))
1000
30 GOSUB
I 1 7 0 F(s)= F(s'l)
1000
IUuv
40 PRINTF
GOSUB
I 180 u(rDun
,t* -;50 GOTO20
I r90 S = S - l
, 'i
t 200 RETURN
Akhoush iterationgjvesbener ansversin both of the first
1
ot ricu^'on. reculsionis rhe deriredtech'
i"o
l 0 REM CALLINGPROGRAMTO SOLVETOWEROi
i;; ;""y problem'becauseit sreallvsimplrfiesthe
TIANOIPUZZLE.
;i;i't "*-".pf.:
OF DIS(S
THh NUMBER
toi'ution ntgotlit. and its impleftentationin a BASIC
20 REMT(I) CONTAINS
I.
proSnm.
ONTOWER
30 REMD(I) ISTHETOTALNTMBEROFDISKS.
DES- -..
40 REMEiII ^ND F(I) ARETHESOURCEAND
To\f,er of Hanoi
of
rhe
Towel
TOVERS,
is
nrst
TINATION
problems.lhe
Leasconsidertwo such
ll3 oi. 3 well.knownproblemnicely treatedin a r€cLrrsrve 50 DrME(20),F(20),T(3)
pegsl '
T(l)
60 INPUT
mann;r.Thls problemconshisof threepegs called
to bc
lle
and
70 r(2)=0
I
i. *A b disks.all ot differentradius
""a on ttrepegs.tnitirlly tbe ditksareslickedon pegI
80 r(3)=0
strckea
on
the
bor
disk
with
rhe
lalgest
90 E ( 1=) I
sre.
in ora", ot a".reiting
peg
I
t00 F(1)= 2
iom. tn ttrisproUtem.you must movethe disksfro'n
then
move
0 D(l) = 111;
io oee2 underthe restricttontho! you canonly
you
mly
that
snd
990
1 2 0 GOSUB
one ai r time from one pegto anothel.
r orte The recut_
1 3 0 GOTO60
never strck a lfllger diskon top of a smalJe
REM SUBROUTINEIOOOCALCULATESTHE
NTH FIBONACCINUII,IBER
IT IN F''
RENIITLRAIIVFLY ANDRETURNS
980
1000 F = 1
l0l0
FORI=ITON'l
t0l0
970
the Ploblemof movingD
sivesohrrion,wliich genetrtizes
peg
F,
movesthe top D-l dhks
to
e
peg
catled
Jis* lrom a
peg,
the onerem'iningditk
moves
then
third
E
to
i
on oer
e ,o p"g F. Jnd thenmovesall of.thediskson the
on p.!'o.n
,o p"c f. In lhis wov.the problemot movinSD
,frira
aisksis reducid to makingtwo movesof Dl disksThere'
fore. the recursivealgoriGmfor movingthe toP D disks
from pegE to PegF is:
l. IID =1.movetopdiskfromE to F andleturn'
2. trt C be the oumberofthe pegwhichis not E ot F'
3. R€cursivelycall this procedrrc to move the top Dl
diskfrom E lo G4. Movelhe disk on E to F.
5. Recursivelycall this procedure!o move the top D-l
diskfrornC to F.
6. Return.
storethe numberofdiskson peg
In the implem€nlalion.
=
I n r T ( l t .f o ; I l , : . i . $ l r r n J t e . u r s i v e ( 1 li l\ m z d et h e
lJluesthrl needsrling-re L. F andD Then the BASIC
versionof thisrlgorithmi
REM TOWER OF HArr'OI SUBROUTI'\"ETO
960
MOVETIIE TOPD(S)DISKS
g,7O REM FRO]UPEC E(S)TO PEGF(S)-T(I) CONTAINS THtl r't-IUBER
'
gIiO
REiIIOF IJISKSOT-PEC I. INITIAL CALL IS
TO 990.
990
S= I
ro00 IF D(s)<> I THEtil0s0
= T(E(sD
-I
1010 T(tds))
Quicksortalgorillrm
of rccursion,
a tinalusefulapplicalion
[rt's now consider
pro8lam
theseeffi'
e3sily
You
crn
rlgorilh'n.
thequicksort
c|enl
and wiJelv_usedsortinS fllSorilhmsIeculsively
'
A(L)."'AGr)
supoo"ett'"i vou tru"esLredvaluesin
wiin to otaci themir) rrcendingorderin lhe sarnesloft
"na
acelocations.The brsic quicksortalSorithmchooc€ssome
=
aibitrrrv valuefiom ihis Lsl. say X A(K)' and lhen relhtn X arelosmcller
rll
vahres
thrl
arranae;lhc valuesso
than X arelo'
valu€s
largcr
all
list
and
the
cateibefore it in
so(€d
correct
rt
its
will
locrted
X
be
it.
Then
rfter
cated
oosilror)irr the li5l of, sav,A(l) TlresrmealSorithrnis then
wilh L .nd I-l in placeof L and H. and
;cdriivelv aDDIied
*irtr t+l anJ ll $hen callingthe 'lgott'en
wilh "pptiea.
L = ll, it sinrplyrelurrrs.
rilhm"e"in
The only parLof lhe slgodlhnrthJt needssotneaddi
thelisl sothrl
of terrrunging
ri,nalartcnrn'nis Ihe process
vrlues
lic nn r\c
ollrc'
pr.'rcr
xr)J
.tll
X L in il\
Iosiliun
l andJ. tou re'
oroLcr sideof X. Ilv kccprnJtwo polr)lers.
rrrelisr.I sllrt\ bv pointingrt the firstPulilion'n
aqanqe
'iir.
downlhe
| . J po;rrsto lt. Tltrnrs poinletI nroves
ihe
valueof
This
thrn
X.
vrlue
no
srnrller
a
lisr.ir elco'rirter'
belowX rtrIhelist.Ne\1,pointe'
AllI \Io ld- drerelore.lie
J DrcvesuD the tist unlil it enco$nteB3 numberno hrger
wirh A(l):borlta(' rhen
thdnX. Tlirt nuNberis e\chrnged
to lhe eventusl
relllive
Posr'
in thc DroocroJrl of the t;l
procers
I
strtlI ctoss.At l\itl
unlil
rioll olrX. Re;c,t the
poinl, the rer;angementis conlpl.le,lrsthe followingex'
shows:
anrpleof the process
l>t2.
,,, ?t.
60,
"-
-E:
.,,
':d
44
1 3 .r->rt l
l3
x->46 JX->46 . J&>45
60 -..60
.L>:t4
94
94
94
49
49
4t
95
95
95
, l7i_-,;..;r ?5
. r. E
x->46.
l->60 . i
94
49 1
95
The folowing programimplementsthis proccss:
TO REAR.
950
REM QUICKSORT-SUBROT]TINE
RANCE A(L(s) rHRU A(H(S))
REM SO TITAT Al-L VALUES <= X LIE BE.
960
FOREX AND ALL VALUES
9'lO
REM >= X LIE AFTER X IVHEREX = A (lNT
&-lt'
'
Sraremenrl0OOin this prosmmis the ten f"r t .-i""1
.
I
l0l0-l I70 pe.formthepdti!oningof the
tion-SraremenIs
list into thosevalue!smallerthan X and thoselarger thtn X. --, :*:.:
Two recursive
callsfollow lhe p.rrtitioning-Only th.ee vBl- .: :: ' i
:
callu€s,1,L andH,aresavedduringthe recursive
Quicksortexample
An illuslrationof an executionof the quicksortalgorithm
appears
asfollows.The far left columnconlainsthe original
The circlednumbersarelha valuesused
list often numbers.
arethe valuesofL
for X, andthe number-pairs
in rectangles
andH usedto prrrition the lisr.Note that the procedur€bcginswith L= l, H - 10, X =46. Partitioninginthc fifth po-.
sitioo then placesX- Next the proc€ssis calledfor X = 3,
L = l, H = 4, andX = 49, L= 6,H - 10.Theprocesscon.
tinuesin thisway until all valuesrre correcdysorted.
t
.. I
I
,. i
'_''
I.l
'::.1I
(L(s) + H(s)/z)).
REM INITIAL CALL TO 99O SORTSA(I)
THRUA(N).
990
S =I
L(l)= I
994
991
H(l) = N
1000 IF L(S)>= H(S)THEN1270
t 0 l 0 M=rNr(L(s)+H(s))/2)
1020 x = A(M)
t030 t = l.(s)
1040 J - ll(s)
I050 I F A ( l ) > - X T H E1N0 8 0
980
r060 l = l + l
1070 coTo 1050
1080
1090
| 100
ll t0
120
t30
140
150
160
t10
180
190
tF A(J)<= X THENI I l0
J=J-l
GOTO1080
I FI > J T H E N
I I70
r = A(t)
A(l) = A(J)
t260 cosuB1000
1210 S - S . l
1280 RETURN
I O RE]\4CALLINGPROCRAMFORQUICKSORT.
20 REM A(1) THROUGTIA(N) CONTAINNU}IBERS
7D
TO BE SORTED.
DrM A(100),L{20),H(20),(20)
INPUTN
FORI=ITON
A(l) = RND(o)
NEXT I
990
80 GOSUB
90
t00
Ilo
r20
of
Th€sefew examplesindicatelhe easeand convcnience
,
doing r€cursionin BASIC. Anotherlargerareaof applica- '.;
' tion for recursioninvolvestr€esearchin8.
This aPPlication . lii
gametreesor for olher rpis especially
usefulfor searching
plicrtionsrhal needa strategyto be dcterminedlhrougha
choicebetweenaltematives.
'l
r(l)=r
l=l+l
J=J-l
IF I <= J THEN1050
I(s) - I
S=S+l
1200 L(s)= L(91)
r2 l 0 H(s) - J
1220 cosuB t 000
1230 S = S + l
=(s-r)
1240 L(s)
H(s)=
H(S'l)
r250
30
40
50
60
Treesearching
FORI=ITON
PRINTA(I)I
NEXTI
coTo 40
24 OlgitalD.{*F JULYt980
THEAUTHOR
ABOUT
Herbe Dershemis Chahmanof the DePartmcntof ComIlolland,Michigan.llehasa
puter Scienceat HopeColleSe,
Ph.D.ni ComputerSciencefrom PurdueUnivenity.
Rale thisarticle: circle 6L,6M or 6H
on Reador lnquiry Card.
lf youraddresslabelis print€din red,
peelofflabel,aftixtolormon pag€t 1'
fill out totm andreturnto usto
continueyour tlee subsctiplion.'
Download