Basic SAS codes for Tower of Hanoi

Reply
Frequent Learner
Posts: 1

Basic SAS codes for Tower of Hanoi

[ Edited ]

Hi everyone, i am currently working on an assignment related to Tower of Hanoi. However, i am unsure about part of the codes, please feel free to check it out and provide some guidance for me, Thanks!!

data tofhanoi;

array H[5,3];

do i= 5 to 1 by -1;

H[i,1]=i;

end;

r3=6; r2=6; r1=1;

do until (r3=1); ;

move=0;

do until (move=1);

check=0;

do until (check=1);

 

/********************************* in here i have to input codes to pick a disk from a tower, which F is the tower number, may i ask how to accomplish here? ************************************/

 

if F=1 & r1 ne 6 then do;

check=1;

r=r1;

end;

else if F=2 & r2 ne 6 then do;

check=1; r=r2;

end;

else if F=3 & r3 ne 6 then do;

check=1; r=r3; end;

end;

 

check=0; ....... (remaining other codes)

Thanks for helping!

PROC Star
Posts: 2,332

Re: Basic SAS codes for Tower of Hanoi

Posted in reply to Stepkwan96

It is difficult to perform recursions from within a data step.

 

Here is a standard solution implemented with macros.

  %macro hanoi(disk, from, to, via); 
    %if &disk.=0 %then %return;
    %hanoi ( %eval(&disk.-1), &from., &via., &to.  );
    %put Move top disk &disk. from tower &from. to tower &to. ; 
    %hanoi ( %eval(&disk.-1), &via. , &to. , &from.) ;
  %mend;
  %hanoi(3,A,B,C); 
Move top disk 1 from tower A to tower B
Move top disk 2 from tower A to tower C
Move top disk 1 from tower B to tower C
Move top disk 3 from tower A to tower B
Move top disk 1 from tower C to tower A
Move top disk 2 from tower C to tower B
Move top disk 1 from tower A to tower B

 

Ask a Question
Discussion stats
  • 1 reply
  • 388 views
  • 4 likes
  • 2 in conversation