用于在c中创建螺旋形图案的嵌套循环 [英] Nested loops for creating a spiral shape pattern in c

查看:136
本文介绍了用于在c中创建螺旋形图案的嵌套循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用嵌套的for循环制作由星号'*'组成的螺旋图案.我设法画出外线,现在我不知道如何在同一位置重复较小的漩涡. 我应该拥有的东西:

I need to make a spiral pattern made of stars '*' using nested for loops. I managed to make outter lines, now I don't know how to repeat smaller swirls in the same place. What I should have:

*********
        *
******* *
*     * *
* *** * *
* *   * *
* ***** *
*       *
*********

任何帮助将不胜感激.

推荐答案

经过彻底书呆子 ,我想到了这一点:

After being thoroughly nerd-sniped, I came up with this:

#include <stdio.h>

void print_spiral(int size)
{
    for (int y = 0; y < size; ++y)
    {
        for (int x = 0; x < size; ++x)
        {
            // reflect (x, y) to the top left quadrant as (a, b)
            int a = x;
            int b = y;
            if (a >= size / 2) a = size - a - 1;
            if (b >= size / 2) b = size - b - 1;

            // calculate distance from center ring
            int u = abs(a - size / 2);
            int v = abs(b - size / 2);
            int d = u > v ? u : v;
            int L = size / 2;
            if (size % 4 == 0) L--;

            // fix the top-left-to-bottom-right diagonal
            if (y == x + 1 && y <= L) d++;

            printf((d + size / 2) % 2 == 0 ? "X" : " ");
        }

        printf("\n");
    }
}

正如其他人所提到的,分配一个代表网格的数组,然后将螺旋线绘制到该数组中(可以在其中自由移动),然后打印该数组可能更直观.但是,此解决方案使用O(1)内存.

As others mentioned, it might be more intuitive to allocate an array representing the grid, and draw the spiral into the array (within which you can move freely), then print the array. But, this solution uses O(1) memory.

几乎可以肯定的是,它可以进行一些优化和简化,但是我会把它留给读者练习",因为我已经花了太多时间了;-)

It could almost certainly be optimized and simplified a bit, but I'll "leave that as an exercise for the reader" as I've already spent too much time on this ;-)

我不会再花时间在此上,但是我有第二次尝试,可能会可能生成更简单的代码.如果您以越来越大的尺寸检查输出,则会出现一种模式:

I'm not going to spend any more time on this, but I had an idea for a second attempt that might result in simpler code. If you check the output at increasingly large sizes, a pattern emerges:

在每个象限内,图案是规则的,可以轻松编码.我认为您只需要将( x y )坐标仔细地分类为四个象限之一,然后应用适当的模式即可.

Within each quadrant, the pattern is regular and can be easily coded. I think you would just have to carefully classify the (x, y) coordinates into one of the four quadrants and then apply the appropriate pattern.

这篇关于用于在c中创建螺旋形图案的嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆