我正试着用一定数量的星星做一个倒金字塔。
当我们知道行数时,任何人都可以画出倒金字塔。
我们可以做这样的倒金字塔
#include <stdio.h>
int main()
{
int i, space, rows, k=0, count = 0, count1 = 0;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1; i<=rows; ++i)
{
for(space=1; space <= rows-i; ++space)
{
printf(" ");
++count;
}
while(k != 2*i-1)
{
if (count <= rows-1)
{
printf("%d ", i+k);
++count;
}
else
{
++count1;
printf("%d ", (i+k-2*count1));
}
++k;
}
count1 = count = k = 0;
printf("\n");
}
return 0;
}Result
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*但就我而言,我想制造一个倒金字塔。在询问了星星的数量后,我想要做金字塔形状。我无法决定有多少行将使它像一个倒金字塔。
(不低于标准只供参考-不是必须遵循相同的模式,有人说,如果你有多少次开始,你会如何安排这些恒星,使其形状像倒金字塔(这可能是不完整的),根据我的想法,打印的形状如下,但这些不是均匀的)。
**Case** :
1. User Enters : 9
* * * * *
* * *
*
2. User Enters : 8
* * * *
* * *
*
3. User Enters : 7
* * * *
* * *
(No matter if shape completes or not, but it should print like this)
4. User Enters : 6
* * *
* *
* 有可能从给定的星星数中决定行数吗?
我将利用这个逻辑在scrollView中创建一个动态视图。
发布于 2018-03-01 08:26:30
这将为您生成金字塔数组,同时尽量减少每个层之间的差异,并保持对称性。
也许还有更多的优化要做,但这是我脑海中出现的第一个想法。
这是在Swift中,可以在Swift游乐场运行,我以为我在OP的帖子下面看到了一个Swift标签,但是现在它显然被删除了,无论如何,代码本身很简单.
func genPyramid(count: Int) -> [Int] {
var result: [Int] = []
var maxPossibleRow: Int
// special case
if count <= 2 {
return [count]
}
// test row diff: 1
maxPossibleRow = Int(floor((sqrt(Float(8*count+1))-1.0)/2.0))
if maxPossibleRow > 1 {
let base = count - maxPossibleRow * (maxPossibleRow-1) / 2
if base % maxPossibleRow == 0 {
let firstRow = base / maxPossibleRow
for k in 1...maxPossibleRow {
result.append(firstRow + k - 1)
}
return result
}
}
// test row diff: 2
maxPossibleRow = Int(floor(sqrt(Float(count))))
if maxPossibleRow > 1 {
let base = count - 2 * maxPossibleRow * (maxPossibleRow-1) / 2
if base % maxPossibleRow == 0 {
let firstRow = base / maxPossibleRow
for k in 1...maxPossibleRow {
result.append(firstRow + 2*k-2)
}
return result
}
}
// test row diff> 3
for i in 3...count/2 {
maxPossibleRow = Int(floor((Float(i-2)+sqrt(Float(i*i-4*i+4+8*i*count)))/2.0/Float(i)))
print("looping", i, maxPossibleRow)
if maxPossibleRow > 1 {
let base = count - i * maxPossibleRow * (maxPossibleRow-1) / 2
if base % maxPossibleRow == 0 {
let firstRow = base / maxPossibleRow
for k in 1...maxPossibleRow {
result.append(firstRow + i*(k-1))
}
return result
}
}
}
return []
}一些测试用例fyr。

发布于 2018-03-01 07:40:17
好吧,有一件事你需要决定你想要建造什么样的金字塔形状,规则是什么?上面显示了一些不同的方案,用于特定数量的恒星,但它们并不遵循建立金字塔的固定模式。
例如,在第一个例子中,有3颗星,后面跟着1颗星,但在最后一个例子中,3颗星和2颗星。对于这种依赖于恒星数量的特殊金字塔设计,您可能需要对其进行某种程度的硬编码。
但是,如果你想要构建的金字塔有一个更精确的定义,例如,每一层不应该比它下面的层多出一颗星,那么你可能可以设计一种算法来为任意数量的恒星找到行数。
这个算法似乎是一个很好的开端,甚至是你想要的:
int main(void)
{
// creating two variables
int num;
printf("Enter num stars: ");
scanf("%d", &num);
printf("\n");
int i = 0;
while (num > i) {
i++;
num -= i;
}
printf("%d rows\n", i);
return 0;
}我把它建立在一个perfect金字塔上,在这个金字塔中,每一行都有一颗恒星,每一行的恒星数和那一行的水平完全一样。点有1颗星,下一行有2,下一行有3,等等.
所以,如果你数数行,减去与你刚才计算的行相等的星星数,然后继续这样做,直到你没有足够的星星来整行为止,你就会得到合适的行数。剩余的星星应该添加到现有的行中,而不是新建一行。
https://stackoverflow.com/questions/49044665
复制相似问题