How to resolve the algorithm Towers of Hanoi step by step in the Objective-C programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Towers of Hanoi step by step in the Objective-C programming language
Table of Contents
Problem Statement
Solve the Towers of Hanoi problem with recursion.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Towers of Hanoi step by step in the Objective-C programming language
Source code in the objective-c programming language
#import
@interface TowersOfHanoi: NSObject {
int pegFrom;
int pegTo;
int pegVia;
int numDisks;
}
-(void) setPegFrom: (int) from andSetPegTo: (int) to andSetPegVia: (int) via andSetNumDisks: (int) disks;
-(void) movePegFrom: (int) from andMovePegTo: (int) to andMovePegVia: (int) via andWithNumDisks: (int) disks;
@end
#import "TowersOfHanoi.h"
@implementation TowersOfHanoi
-(void) setPegFrom: (int) from andSetPegTo: (int) to andSetPegVia: (int) via andSetNumDisks: (int) disks {
pegFrom = from;
pegTo = to;
pegVia = via;
numDisks = disks;
}
-(void) movePegFrom: (int) from andMovePegTo: (int) to andMovePegVia: (int) via andWithNumDisks: (int) disks {
if (disks == 1) {
printf("Move disk from pole %i to pole %i\n", from, to);
} else {
[self movePegFrom: from andMovePegTo: via andMovePegVia: to andWithNumDisks: disks-1];
[self movePegFrom: from andMovePegTo: to andMovePegVia: via andWithNumDisks: 1];
[self movePegFrom: via andMovePegTo: to andMovePegVia: from andWithNumDisks: disks-1];
}
}
@end
#import
#import "TowersOfHanoi.h"
int main( int argc, const char *argv[] ) {
@autoreleasepool {
TowersOfHanoi *tower = [[TowersOfHanoi alloc] init];
int from = 1;
int to = 3;
int via = 2;
int disks = 3;
[tower setPegFrom: from andSetPegTo: to andSetPegVia: via andSetNumDisks: disks];
[tower movePegFrom: from andMovePegTo: to andMovePegVia: via andWithNumDisks: disks];
}
return 0;
}
You may also check:How to resolve the algorithm Leap year step by step in the Standard ML programming language
You may also check:How to resolve the algorithm Singly-linked list/Traversal step by step in the Wren programming language
You may also check:How to resolve the algorithm Perfect numbers step by step in the PHP programming language
You may also check:How to resolve the algorithm Idiomatically determine all the lowercase and uppercase letters step by step in the MiniScript programming language
You may also check:How to resolve the algorithm Repeat step by step in the Modula-2 programming language