#!/usr/bin/perl -w

$PARTIES = 10;

$SEATS = 135;

$POPULATION = 5_000_000;

# $GR = $VOTES / $SEATS; # golden ratio

# Improving D'Hondt law

for (1..$PARTIES){
    $ran[$_] = rand();
    $sumran += $ran[$_];
}
for (1..$PARTIES){
    $ran[$_] /= $sumran;
}

for (1..$PARTIES){
    $p[$_] = int $ran[$_] * $POPULATION;
    $sum += $p[$_];
    print "Partido $_ -> $p[$_] votos\n";
}
print "VOTOS TOTALES: $sum\n"; 
$GR = $sum / $SEATS;
print "Ratio: $GR\n";



for (1..$PARTIES){    
    $r[$_] = $p[$_] / $GR - int ($p[$_]/$GR);
}

# Assingning the even seats 

for $i (1..$PARTIES) {
    for (1.. $SEATS){
	if ($p[$i] >= $GR){
	    $count++;
	    $seat{$count} = $i; 
	    $p[$i] -= $GR;
	}else { last; }
    }
    $remainder{$i} = $r[$i];
#    $rem{ $r[$i] } = $i;
}

# Assingning the odd seats

$odd = $SEATS - $count;
print "There are $odd odd seats.\n";
@list = sort { $remainder{$b} <=> $remainder{$a} } keys(%remainder);
for (0..$odd-1) {
    $count++;
    $seat{ $count } = $list[$_];
    last if $count == $SEATS;
}

for (sort { $a <=> $b } keys %seat) {
    print "$seat{$_} ";
}

print "\n";

__END__
  
In 21th December 2017 there was autonomic elections in Catalonia.
  For 135 seats and around 82% of population (5M) voters,
  Hondt law assigned 72 seats to the separatist, despite the
  fact that there are more votes to the non separatist.
  Around 150K more. This was a mayor fault of the law, and science.
  Since the mayority is reached with 68 seats, the error is in
  at least 5 seats, out of 135.

BUGS
  Empates. Y lo que se ha denominado $POPULATION son los votos válidos.
  
