Ocena użytkownikóww: ***** / 1
Nadesłany przez Tomasz Lubiński, 22 kwietnia 2006 01:00
Kod przedstawiony poniżej przedstawia główną część rozwiązania problemu.
Pobierz pełne rozwiązanie.Jeżeli nie odpowiada Ci sposób formatowania kodu przez autora skorzystaj z pretty printer'a i dostosuj go automatycznie do siebie.
Hare_Niemeyer.java:
/**
* Algorytm Hare-Niemeyer'a
*
* www.algortym.org
* (c)2006 Tomasz Lubinski
*/
public class Hare_Niemeyer {
/**
* @param args
*/
public static void main(String[] args) {
int mandates[];
int votes[];
float calcTab[];
float max;
int groupCount, mandatesCount, mandatesCounter, votesCount, maxInd = 0;
//get all data
System.out.println("Podaj liczbe partii");
groupCount = Console.readInt("?");
//initialize all tables
mandates = new int[groupCount];
votes = new int[groupCount];
calcTab = new float[groupCount];
System.out.println("Podaj liczbe mandatow");
mandatesCount = Console.readInt("?");
for (int i=0; i<groupCount; i++)
{
System.out.println("Podaj liczbe glosow na partie " + (i+1));
votes[i] = Console.readInt("?");
}
//calculate number of total votes
votesCount = 0;
for (int i=0; i<groupCount; i++)
{
votesCount += votes[i];
}
//initial number of mandates (Hare-Niemeyer)
mandatesCounter = 0;
for (int i=0; i<groupCount; i++)
{
calcTab[i] = (float)(votes[i]*mandatesCount*1.0) / votesCount;
mandates[i] = (int)Math.floor(calcTab[i]);
calcTab[i] -= mandates[i];
mandatesCounter += mandates[i];
}
//calculate rest of mandates
while (mandatesCounter < mandatesCount)
{
max = -1;
for (int i=0; i<groupCount; i++)
{
if (max<calcTab[i])
{
max = calcTab[i];
maxInd = i;
}
}
//give mandate for party with max
mandates[maxInd]++;
mandatesCounter++;
calcTab[maxInd] = 0;
}
//present results
for (int i=0; i<groupCount; i++)
{
System.out.println("Partia " + (i+1) + " ma " + mandates[i] + " mandatow");
}
}
}