码迷,mamicode.com
首页 > 其他好文 > 详细

Complete The Pattern #6 - Odd Ladder

时间:2015-07-01 20:34:07      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

Complete The Pattern #6 - Odd Ladder

Task:

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.

Examples:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!