Complete The Pattern #2
Description:
Task:
You have to write a function pattern which creates the following pattern upto n number of rows. If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string.
Pattern:
(n)(n-1)(n-2)...4321
(n)(n-1)(n-2)...432
(n)(n-1)(n-2)...43
(n)(n-1)(n-2)...4
...............
..............
(n)(n-1)(n-2)
(n)(n-1)
(n)
Examples:
pattern(4):
4321
432
43
4
pattern(6):
654321
65432
6543
654
65
6
Note: There are no blank spaces
Hint: Use
in string to jump to next line
之前做的几个练习题,看别人用Linq用的那么溜,看起来高大上,所以自己研究了一下,也开启了装逼模式
using System; using System.Linq; public class Kata { public string Pattern(int n) { string result = string.Empty; if (n > 0) { result = string.Join(Environment.NewLine, Enumerable.Range(1, n).Reverse().Select(item => string.Join(string.Empty, Enumerable.Range(n - item + 1, item).Reverse()))); } return result; } }
Enumerable.Range(1, n)得到1,2,3...,9
然后Reverse获取倒序的数字9,8,7,...,1
再通过Select以及lambda表达式针对每一个生成一个不同的结果
item => string.Join(string.Empty, Enumerable.Range(n - item + 1, item).Reverse())
每一个item,生成对应的item,item-1,...,n-item+1 ,然后将这个结果用string.empty连接起来