代码很简单,但算法很经典,话不多说,直接上代码。

    public struct ServerConfig
    {
        /// <summary>
        /// 初始权重
        /// </summary>
        public int Weight { get; set; }
        /// <summary>
        /// 当前权重
        /// </summary>
        public int Current { get; set; }
        /// <summary>
        /// 服务名称
        /// </summary>
        public string Name { get; set; }
    }

  

        public static int NextServerIndex(ServerConfig[] ss)
        {
            int index = -1;
            int total = 0;
            int size = ss.Count();    

            for (int i = 0; i < size; i++)
            {
                ss[i].Current += ss[i].Weight;
                total += ss[i].Weight;

                if (index == -1 || ss[index].Current < ss[i].Current)
                {
                    index = i;
                }
            }

            ss[index].Current -= total;
            return index;
        }

  

        static void Main(string[] args)
        {

            var sv = new ServerConfig[] {
                new ServerConfig{ Name="A",Weight=4},
                new ServerConfig{ Name="B",Weight=2},
                new ServerConfig{ Name="C",Weight=1}
            };

            int index = 0;
            int sum = sv.Sum(m => m.Weight);
            for (int i = 0; i < sum; i++)
            {
                index = NextServerIndex(sv);
                Console.WriteLine("{0} {1}", sv[index].Name, sv[index].Weight);
            }

            Console.Read();
        }

  参考文献:http://blog.csdn.net/gqtcgq/article/details/52076997

      文章出处:http://www.cnblogs.com/anech/p/6704240.html

 

      转载请注名出处,谢谢!  

 

   

相关文章:

  • 2021-11-17
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-09
  • 2021-08-25
  • 2021-04-01
猜你喜欢
  • 2021-07-03
  • 2021-08-18
  • 2022-01-25
  • 2022-12-23
  • 2021-09-15
  • 2021-12-13
  • 2022-12-23
相关资源
相似解决方案