我最近一直在寻找一些简单的编码挑战,并发现了关于 Pascal 的三角形(在这里),并且我尝试在 C/Objective-C 中自己生成一个。对于那些不知道它是什么的人,该链接很好地解释了它。
在第四排之后我开始变得奇怪,我就是不知道为什么。
我的 5 次迭代的输出当前如下所示:
1
1 1
1 2 1
1 3 3 1
4 6 3 1
它应该如下所示:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
到目前为止,这是我的代码。第一个循环只是一个重置循环(将所有值设置为 0)。实际的逻辑主要发生在第二个循环中。第三个循环是将值连接并格式化为字符串的地方。
为了提高可读性,我对这段代码的评论比我自己评论的要多得多。
int iterations, i, b, mid, chars, temp;
NSLog(@"Please enter the number of itereations");
scanf("%i",&iterations); // take users input and store it in iterations
// calculate where the first 1 should go.
if (iterations % 2 == 0) mid = (iterations)/2;
else mid = (iterations+1)/2;
chars = iterations*2;
int solutions[iterations][chars];
// reset loop
for (i = 0; i<iterations; i++) {
for (b = 0; b<chars; b++) {
solutions[i][b] = 0;
}
}
solutions[0][mid] = 1; // place the initial 1 in first row
for (int row = 1; row<iterations; row++) {
for (int chi = 0; chi<chars; chi++) {
temp = 0;
if (chi > 0) {
temp += solutions[row-1][chi-1]; // add the one diagonally left
}
if (chi < iterations) {
temp += solutions[row-1][chi+1]; // add the one diagonally right
}
solutions[row][chi] = temp; // set the value
}
}
// printing below...
NSMutableString *result = [[NSMutableString alloc] initWithString:@"\n"];
NSMutableString *rowtmp;
for (i = 0; i<iterations; i++) {
rowtmp = [NSMutableString stringWithString:@""];
for (b = 0; b<chars; b++) {
if (solutions[i][b] != 0) [rowtmp appendFormat:@"%i",solutions[i][b]];
else [rowtmp appendString:@" "]; // replace any 0s with spaces.
}
[result appendFormat:@"%@\n",rowtmp];
}
NSLog(@"%@",result);
[result release];
我感觉问题可能与偏移有关,但我不知道如何解决它。如果有人能发现我的代码出错的地方,那就太好了。