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

48行代码解一道亚马逊的在线笔试题

时间:2014-11-07 20:41:17      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   ar   os   sp   for   

这题是我从这里看到的一道亚马逊的在线笔试题,具体规则请前往该文章查看,下面贴出我的解题代码:

其中11,12,13,14分别代表J,Q,K,A;

 

      class CardCompare
        {
            private int[] cards = new int[] { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };
            public bool CompareCards(int[] cards1, int[] cards2)
            {
                return cardsScore(cards1) > cardsScore(cards2);
            }
            private double cardsScore(int[] handcards)
            {
                double score = 0;
                handcards = handcards.OrderBy(a => a).ToArray();
                int max = handcards[handcards.Length - 1];
                int min = handcards[0];
                if (max == min)
                {
                    return max * Math.Pow(16, handcards.Length + 8);
                }
                else if (max - min == handcards.Length - 1 && handcards.SequenceEqual(cards.Where(a => a >= min && a <= max).OrderBy(a => a)))
                {
                    return max * Math.Pow(16, handcards.Length + 7);
                }
                else if (min == cards[0] && max == cards[cards.Length - 1] && handcards.SequenceEqual(cards.Where(a => (a >= min && a <= min + (handcards.Length - 2)) || a == cards[cards.Length - 1])))
                {
                    return handcards[handcards.Length - 2] * Math.Pow(16, handcards.Length + 7);
                }

                var dist = handcards.Distinct().Select(a => new Tuple<int, int>(a, handcards.Length - handcards.Where(b => b != a).Count())).Where(a => a.Item2 > 1).OrderByDescending(a => a.Item2).ThenByDescending(a => a.Item1).ToArray();
                for (var i = 0; i < dist.Length; i++)
                {
                    score += dist[i].Item1 * Math.Pow(16, handcards.Length + dist[i].Item2 - i + 2);
                }
                handcards = handcards.Except(dist.Select(a => a.Item1)).OrderBy(a => a).ToArray();
                for (var i = handcards.Length - 1; i >= 0; i--)
                {
                    score += handcards[i] * Math.Pow(16, i);
                }
                return score;
            }
        }

解题思路为根据规则计算手牌的得分,最后对比两副手牌得分,我没有限制牌的张数,4张,5张都可以。

如果大家发现什么问题欢迎留言交流

48行代码解一道亚马逊的在线笔试题

标签:des   style   blog   http   color   ar   os   sp   for   

原文地址:http://www.cnblogs.com/coolray/p/4081990.html

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