首页 > 解决方案 > 打印不重复字符的正方形

问题描述

我想打印一个这样的矩形:

&#*@
#*@&
*@&#
@&#*

但问题是我找不到打印这个的算法。

我只知道如何打印一个简单的矩形/正方形

public static void Main(string[] args)
    {
        Console.Out.Write("Saisir la taille : ");
        int taille = int.Parse(Console.In.ReadLine());
        int i; 
        int j;
        for(i = 0; i < taille; i++){
            for(j = 0; j < taille; j++){
              Console.Write("*");
            }
            Console.WriteLine("");
        } 
    }

谢谢 !

标签: c#

解决方案


首先,除非您需要在循环之外使用迭代器,否则只需在 for 声明中声明它们

public static void Main(string[] args)
    {
        Console.Out.Write("Saisir la taille : ");
        int taille = int.Parse(Console.In.ReadLine());
        for(int i = 0; i < taille; i++){
            for(int j = 0; j < taille; j++){
              Console.Write("*");
            }
            Console.WriteLine("");
        } 
    }

其次,根据您的示例,您需要一个要使用的字符列表

char[] chars = { '&', `#`, `*`, '@' };

我们需要一种方法来知道在任何给定时间我们想要使用哪个字符,比如一个迭代器,我们可以为简单起见调用 characterIndex。我们将在每次迭代中增加它。如果增加它会使它超出我们的字符数组的范围,如果 characterIndex == 4,我们将它设置回零。

int characterIndex;

为了获得你所拥有的滚动效果,在每一行之前,我们必须选择一个被行偏移的字符索引

characterIndex = i % chars.Length;

将它们捆绑在一起

public static void Main(string[] args)
    {
        char[] chars = { '&', `#`, `*`, '@' };
        int characterIndex;
        Console.Out.Write("Saisir la taille : ");
        int taille = int.Parse(Console.In.ReadLine());
        for(int i = 0; i < taille; i++){
            characterIndex = i % chars.Length;
            for(int j = 0; j < taille; j++){
              Console.Write(chars[characterIndex]);
              characterIndex++;
              if(characterIndex == chars.Length)
                  characterIndex = 0;
            }
            Console.WriteLine("");
        } 
    }

推荐阅读