标签:
You have to write a function pattern
which creates the following pattern (see examples) up to the desired number of rows.
If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string.
If any even number is passed as argument then the pattern should last upto the largest odd number which is smaller than the passed even number.
pattern(9):
1
333
55555
7777777
999999999
pattern(6):
1
333
55555
Note: There are no spaces in the pattern
Hint: Use \n in string to jump to next line
using System; using System.Collections.Generic; using System.Linq; public static class Kata { public static string OddLadder(int n) { string result = string.Empty; List<int> list = new List<int>(); for (int i = 1; i <= n; i = i + 2) { list.Add(i); } result = string.Join("\n", list.Select(item => Selector(item))); return result; } public static string Selector(int number) { string str = string.Empty; for (int i = 0; i < number; i++) { str = str + number.ToString(); } return str; } }
Linq中的Select
//public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector);
Func<TSource, TResult>泛型委托
//public delegate TResult Func<in T, out TResult>(T arg)
其他人的解法:
using System; using System.Linq; public static class Kata { public static string OddLadder(int n) { if (n <= 0) return String.Empty; var oddNumbers = Enumerable.Range(1, n).Where(i => i % 2 == 1); var lines = oddNumbers.Select(i => String.Join("", Enumerable.Repeat(i.ToString(), i))); return String.Join(Environment.NewLine, lines); } }
Complete The Pattern #6 - Odd Ladder
标签:
原文地址:http://www.cnblogs.com/chucklu/p/4613934.html