打印字母作为char的钻石

时间:2018-05-31 14:13:55

标签: c# algorithm

这个算法有问题; 我可以用迭代循环来做,但我想知道我怎么能用递归来做 你能帮帮我吗?

我只使用c#进行演示,我想知道的是算法,我无法弄清楚诀窍在哪里 感谢

int nbl = 10;
for (int i = 0; i < nbl; i++)
{
    int esp = nbl - i - 1;
    for (int j = 0; j < esp; j++)
    {
        Console.Write(" ");
    }
    for (int k = 0; k <= i; k++)
    {
        Console.Write("{0} ", Convert.ToChar(i + 65));
    }
    Console.WriteLine();
}
for (int i = nbl-2; i >= 0; i--)
{
    int esp = nbl - i - 1;
    for (int j = 0; j < esp; j++)
    {
        Console.Write(" ");
    }
    for (int k = 0; k <= i; k++)
    {
        Console.Write("{0} ", Convert.ToChar(i + 65));
    }
    Console.WriteLine();
}
Console.ReadKey();


            A
        B       B
    C       C       C
D       D       D       D
    C       C       C
        B       B   
            A

1 个答案:

答案 0 :(得分:0)

试试这个:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication48
{
    class Program
    {
        const int SIZE = 4;
        const string ThreeSpace = "   ";
        static void Main(string[] args)
        {
            int level = 0;
            Recursive(level);
            Console.ReadLine();
        }
        static void Recursive(int level)
        {
            string leader = "";
            string text = "";
            int index = 0;

            if(level >= (2 * SIZE) - 1) return;

            if (level < SIZE)
            {
                //grow larger
                index = SIZE - level - 1;
                text = string.Join(ThreeSpace, new string((char)(index + 65), level + 1).Select(x => (char)(level + 65)));
            }
            else
            {
                //grow smaller
                index = level - SIZE + 1;
                text = string.Join(ThreeSpace, new string((char)(index + 65 - 1), SIZE - index).Select(x => (char)(SIZE - index + 65 - 1)));
             }
            leader = new string(' ', 2 * index);
            Console.WriteLine(leader + text);
            Recursive(level + 1);

        }
    }
}