hans.hu

夫天地者,万物之逆旅也;光阴者,百代之过客也。而浮生若梦,为欢几何?古人秉烛夜游,良有以也。况阳春召我以烟景,大块假我以文章。

趣味编程(一)

1、需求:找出一个给定字符串中每个字符及其重复次数,同时获取出重复次数最多的字符。

public static T MaxElement<T, TCompare>(this IEnumerable<T> collection, Func<T, TCompare> func) where TCompare : IComparable<TCompare>
{
    T maxItem = default(T);
    TCompare maxValue = default(TCompare);
    foreach (var item in collection) {
        TCompare temp = func(item);
        if (maxItem == null || temp.CompareTo(maxValue) > 0) {
            maxValue = temp;
            maxItem = item;
        }
    }
    return maxItem;
}
string findStr = "Beijing";
var rm = findStr.ToCharArray().GroupBy(c => c).Select(g => new { g.Key, Count = g.Count() }).MaxElement(r => r.Count);

2、需求:生成不重复的随机数并排序。

public static IList<int> GetRandoms(int min, int max, int length)
{
    IList<int> rlist = new List<int>();
    int index = 1;
    int seed = new Random().Next();
    while (index < length) {
        var random = new Random(seed++).Next(min, max);
        if (!rlist.Contains(random))
            rlist.Add(random);
        index = rlist.Count();
        Console.WriteLine(index);
    }

    return rlist;
}
List<int> rlist = GetRandoms(10, 99, 20).ToList();
rlist.Sort((x, y) => Math.Sign(x - y));

posted on 2010-10-29 21:51  hans.hu  阅读(726)  评论(4编辑  收藏  举报

导航