Re: a problem in my program in pascal
- From: "Tom de Neef" <tdeneef@xxxxxxxx>
- Date: Wed, 11 Oct 2006 18:53:05 +0200
<gilevgi@xxxxxxxxx> schreef in bericht
news:1160569433.506935.220260@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
I want to write the pattern " for i:=1 to a[i] do" n times (n is
variable), that is,
for b[1]:=1 to a[1] do
for b[2]:=1 to a[2] do
for b[3]:=1 to a[3] do
for b[4]:=1 to a[4] do
.........
..........
.........
for b[n]:=1 to a[n] do
something here.
in this writing n is a variable. therefore I can not write what i want.
can you say how can i write the above structure using "repeat-until" or
"while" patterns?
This is a common problem in game theory for N*N boards and quantum mechanics
for N particles.
Think about the problem of puting N queens on a N*N chessboard, such that
they can not catch each other.
The trick is to see the recursion in it. When you've structurally solved it
for K loops, you have essentially solved it for K+1 loops as well.
The trivial example of recursion is the calculation of faculty(N): (N * N-1
* N-2 * .. *1). Since N! = N *(N-1)!, the function can be defined as
(barring negative arguments):
function faculty(N:integer);
begin
if N>1
then result:=N*faculty(N-1)
else result:=1
end;
It is perfectly acceptable to call the function from within itself. Try it !
In your case you could argue as follows:
if I have a (rudimentary) procedure LOOPS(N : integer) that does what I want
to do for N nested loops, then the body of that procedure will look like:
procedure LOOPS(N,kmax : integer);
var k : integer;
begin
if N=0
then DoSomthing
else for k:=1 to kmax do LOOPS(N-1)
end;
In your case kmax is not a constant but varies per loop and DoSomething may
need the values of all the loop counters (k). Hence, these need to be
incorporated as parameters for the function. So you get
procedure LOOPS(N : integer; KMAXs : array of integer; var LOOPCOUNTERs :
array of integer);
var k : integer;
begin
if N<=0
then DoSomething(LOOPCOUNTERs)
else for k:=1 to KMAXs[N] do
begin LOOPCOUNTERs[N]:=k;
LOOPS(N-1,KMAXs,LOOPCOUNTERs)
end
end;
If DoSomething needs more arguments (eg, the original N), then that should
be passed as a parameter to the function as well. And the order of the
values in LOOPCOUNTERs may be the reverse of what you want, and a few more
things are to be addressed as well.
And beware that debugging recursive procedures may be confusing.
Tom
.
- References:
- a problem in my program in pascal
- From: gilevgi
- a problem in my program in pascal
- Prev by Date: Re: a problem in my program in pascal
- Next by Date: Re: Interface Question
- Previous by thread: Re: a problem in my program in pascal
- Index(es):
Relevant Pages
|