固定金額和人數紅包分配算法

轉自:http://www.cnblogs.com/wicub/p/6096897.html
 
/// <summary>
        /// 生成紅包數組
        /// </summary>
        /// <param name="totalMoney">總金額</param>
        /// <param name="perMax">最大金額</param>
        /// <param name="perMin">最小金額</param>
        /// <param name="totalUser">總人數</param>
        static decimal[] CalueHB(int totalMoney, decimal perMax, decimal perMin, int totalUser)
        {
            int i = 0; //第幾人
            decimal[] array = new decimal[totalUser];//分配結果集            
            Random ran = new Random();

            for (i = 0; i < totalUser; i++) //保證每一個人有最小金額+隨機值
            {
                array[i] = perMin + Math.Round((Convert.ToDecimal(ran.NextDouble()) * (totalMoney / totalUser - perMin - 1)), 2);
            }

            decimal yet = array.Sum(); // 已分配的總金額
            decimal thisM = 0M; //當前隨機分配金額

            while (yet < totalMoney)
            {
                thisM = Math.Round((Convert.ToDecimal(ran.NextDouble()) * (perMax - perMin - 1)), 2);

                i = ran.Next(0, totalUser); //隨機選擇人
                if (yet + thisM > totalMoney)
                {
                    thisM = totalMoney - yet;
                }

                if (array[i] + thisM < perMax)//判斷是否超出最大金額
                {
                    array[i] += thisM;
                    yet += thisM;
                }
            }


            Array.Sort(array);

            yet = 0;
            for (i = 0; i < totalUser; i++)
            {
                yet += array[i];
                Console.Write("第{0}人=>分配{1}元,合計分配{2}元\r\n", (i + 1).ToString().PadLeft(3, ' '), array[i].ToString("f2").PadLeft(8, ' '), yet.ToString("f2").PadLeft(8, ' '));
            }

            return array;
        }
相關文章
相關標籤/搜索