zoukankan      html  css  js  c++  java
  • largest remainder method java impl

    /**
     * 最大余数分摊算法
     * 
    @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;
        }
    }
  • 相关阅读:
    第一篇代码 嗨翻C语言 21点扑克
    Windows7 sp1 64位下安装配置eclipse+jdk+CDT+minGW
    MinGW-64 安装
    Windows Live Writer配置步骤
    Css 居中
    c++ 常量成员函数
    c/c++ 引用计数
    C++ 《STL源码剖析》学习-vector
    C/C++ 有符号数和无符号数
    cocos2d 内存管理机制
  • 原文地址:https://www.cnblogs.com/xhan/p/2328955.html
Copyright © 2011-2022 走看看