Complete The Pattern #6 - Odd Ladder

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)

 

 

其他人的解法:

System.Linq命名空间下的Enumerable类的使用

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);
  }
}
/// <summary>
/// Generates a sequence of integral numbers within a specified range. 
/// </summary>
/// <param name="start">The value of the first integer in the sequence.</param>
/// <param name="count">The number of sequential integers to generate.</param>
/// <returns></returns>
public static IEnumerable<int> Range(int start, int count)
{

}

/// <summary>
/// Generates a sequence that contains one repeated value.
/// </summary>
/// <typeparam name="TResult">The type of the value to be repeated in the result sequence.</typeparam>
/// <param name="element">The value to be repeated.</param>
/// <param name="count">The number of times to repeat the value in the generated sequence.</param>
/// <returns></returns>
public static IEnumerable<TResult> Repeat<TResult>(TResult element, int count)
{
}

 

你可能感兴趣的:(Pattern)