c - Tower of Hanoi - User is moving disks (c)
问题描述
I'm currently trying to make a c program that first asks user inputs the number of disks, and then the user is allowed to move the disks freely.
However, it must have the rules of the original Tower of Hanoi, such as the bigger disks cannot be placed over smaller ones.
Also, the poles are '0, 1, 2'
For example,
input : 5
output :
0: 5 4 3 2 1
1: x
2: x
input : 0 1
output :
0: 5 4 3 2
1: 1
2: x
input : 3 3
program ends because there is no pole 3
I would like to get a hint? sort of like a way I can start coding.
Thanks!
解决方案
您可以制作代表 3 个极点的二维数组。
获取用户输入并初始化
arr[2][number] = {0};
for(i=0; i<number; i++){
arr[0][i] = number-i;
}
并启动一个循环,帮助用户输入 2 个数字并操作移动。您需要检查几个条件,例如
- 如果 k > l, arr[x][k] < arr[x][l] 其中 x, k, l 是真数
- 如果输入不是正确的数字(比如你的例子)
也许代码可以如下所示。
scanf("%d %d", &n1, &n2);
while(n1<3 && n1>=0 && n2 <= number &&n2 > 0){
/// deleteDisk: find last component which is not zero and make it zero and return deleted disk size
disk = deleteDisk(arr, n1);
/// addDisk: change first zero to disk, return 0 if violates condition 1
err = addDisk(arr, n2, disk);
if (err == 0)
break;
/// arrayPrint: print 2d array til zero
arrayPrint;
scanf("%d %d", &n1, &n2);
}
推荐阅读
- swift - 如何在 SwiftUI 中将 Date 转换为 DateComponents?
- r - 3D 密度图(来自 3D 散点图)
- java - When are sealed classes and records used together in Java?
- r - 如果 r 函数因任何原因退出,如何保证它会返回一个对象?
- haskell - 从 Yesod 中的 URL 查询中查找参数数组
- android - 为什么在数据类中初始化变量
- python - 如何制作自动填充某些条目的 Tkinter GUI
- docker - 无法在 Synology NAS 中的 Docker 上运行 Gerrit
- ios - 如何格式化右侧相邻的两个 UIBarButtonItem?
- javascript - Should I run reoccuring event every 15 minutes from within mysql, or through javascript?