小寒的blog
Programming is a darned hard thing—but I am going to like it.
posts - 99,  comments - 107,  trackbacks - 0
/**
 * 最大余数分摊算法
 * 
@author xhan
 *{
@link=http://en.wikipedia.org/wiki/Largest_remainder_method}
 
*/
public class ShareCalculator {

    public static  double[] calculate(double[] votes , double totalSeats) {
        double[] seats = new double[votes.length];
        double[] reminders = new double[votes.length];
        
        double totalVotes = 0;
        for (double vote : votes) {
            totalVotes += vote;
        }
        
        double hareQuota = totalVotes / totalSeats ;
        double allocatedSeats = 0;
        
        for(int i = 0; i < votes.length ;i++) {
            double voteDivHareQuota = votes[i] / hareQuota;
            seats[i] = Math.floor(voteDivHareQuota);
            reminders[i] = voteDivHareQuota - seats[i];
            allocatedSeats += seats[i];
        }

        double leftSeats = totalSeats - allocatedSeats;
        
        //allocate left seats to party with largest reminder 
        for (int i = 0; i < leftSeats; i++) {
            double max = 0;
            int maxIndex = 0;
            for (int j = 0; j < reminders.length; j++) {
                if(reminders[j] > max) {
                    max = reminders[j];
                    maxIndex = j;
                }
            }
            seats[maxIndex] += 1;
            reminders[maxIndex] = 0;
        }
        
        return seats;
    }
}
posted on 2012-01-23 14:01 xhan 阅读(12) 评论(0) 编辑 收藏
发表评论

昵称: [登录] [注册]

主页:

邮箱:(仅博主可见)

评论内容:

  登录  注册

[使用Ctrl+Enter键快速提交评论]

0 2328955 YteXiH/A6+E=
昵称:xhan
园龄:4年8个月
粉丝:18
关注:2

<2012年1月>
25262728293031
1234567
891011121314
15161718192021
22232425262728
2930311234

搜索

 

常用链接

最新随笔

我的标签

随笔分类

随笔档案

好友博客

积分与排名

  • 积分 - 39298
  • 排名 - 2733

最新评论

阅读排行榜

评论排行榜

推荐排行榜