zoukankan      html  css  js  c++  java
  • 利用C#迭代器的一个杨辉三角示例

    身边有个朋友在跟着廖雪峰的教程学习python,途中遇到了“在Python中使用迭代器打印杨辉三角”的问题,我在帮忙解决的同时顺手写了个简单的C#版本以供补充。

    internal class Program
        {
            /// <summary>
            ///     打印杨辉三角
            /// </summary>
            /// <param name="count"></param>
            /// <returns></returns>
            private static IEnumerable<List<int>> YanghuiSanjiao(int count)
            {
                var previewList = new List<int>();
                List<int> currentList=new List<int>();
    
                var n = 1;
    
                while (n <= count)
                    if (n == 1 || n == 2)
                    {
                        n = n + 1;
                        currentList.Add(1);
                        previewList = currentList;
                        yield return currentList;
                    }
                    else
                    {
                        currentList = new List<int> {1};
                        foreach (var item in Enumerable.Range(1, n - 2))
                            currentList.Add(previewList[item - 1] + previewList[item]);
                        currentList.Add(1);
                        previewList = currentList;
                        n = n + 1;
                        yield return currentList;
                    }
            }
    
    
            private static void Main(string[] args)
            {
                foreach (var item in YanghuiSanjiao(20))
                {
                    item.ForEach(c =>
                    {
                        Console.Write(c+" ");
                    });
                    Console.WriteLine();
                }
    
                Console.WriteLine("Stop printing");
            }
        }
    

    今早又听到Java9的正式版会有JShell的支持,而不久前推出的C#7中也有了元组的概念,果然不得不概叹现在编程语言的发展已经越来越往函数式编程靠拢了。早几个月之前,我在一篇微信公众号文章上看到了老赵翻译的Anders10年的演讲文章,主题也是关于编程语言的发展趋势和发展方向,这里也顺便贴个链接,作为备忘吧。

  • 相关阅读:
    退役划水一
    Codeforces 1592F2 Alice and Recoloring 2
    AtCoder Regular Contest 108 选做
    AtCoder Regular Contest 107 选做
    AtCoder Regular Contest 106 选做
    AtCoder Regular Contest 105 选做
    2021 年铜陵市青少年编程大赛 部分题解
    Codeforces 1566G Four Vertices
    数据迁移的一般测试步骤
    mac常用命令
  • 原文地址:https://www.cnblogs.com/Wddpct/p/6700524.html
Copyright © 2011-2022 走看看