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

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

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

其中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行代码解一道亚马逊的在线笔试题