my $votes_file = "votes.txt";
sub EffectiveVote (Str $vote, Hash %skip)
{
my @vote = split ',', $vote;
for @vote -> $choice
{
if (! %skip{$choice}.defined)
{
return $choice;
}
}
die "No valid vote?!";
}
sub CountRound (Array @votes, Hash %skip)
{
say "{@votes.elems} votes";
my %count;
my $total = 0;
for @votes -> $vote
{
my $choice = EffectiveVote($vote, %skip);
%count{$choice}++;
$total++;
}
my %percentages;
for %count.keys -> $choice
{
%percentages{$choice} = %count{$choice} / $total;
}
return %percentages;
}
my @votes;
my $votes = open($votes_file);
for (=$votes) -> $vote
{
push @votes, $vote;
}
my $count = 0;
my %skip;
while (1)
{
say;
say "Round {++$count}";
my %percentages = CountRound(@votes, %skip);
my @ordered = sort { %percentages{$^b} <=> %percentages{$^a} }, %percentages.keys;
for @ordered -> $vote
{
say "$vote: {%percentages{$vote}}";
}
if (%percentages{@ordered[0]} > 0.5)
{
say;
say "The winner is {@ordered[0]} with {%percentages{@ordered[0]} * 100.0}% of the vote.";
exit;
}
my $skip = @ordered.pop;
%skip{$skip} = 1;
say "Skipping $skip";
}
Two difficulties of note here. First, I initially tried making @votes an array of arrays. I couldn't figure out any obvious way to make this work in Perl 6. Second problem is
perl6(28102) malloc: *** error for object 0x2eb5a10: double free
*** set a breakpoint in malloc_error_break to debug
Segmentation fault
after the script properly finishes.
EffectiveVote (Score:1)
Re: (Score:1)
returnversusdiehere. (And my wondering is more complicated because I cannot find documentation for.firstanywhere.)If no valid vote is found, won't the first line return undefined rather than not return?
Re: (Score:1)
Argh, yes. Good point.
Re: (Score:1)
do it, in theory? (In practice, I haven't gotten
err dieto work for me yet.)Re: (Score:1)
actually compiled and it works! (I tested created a second votes file to make sure that it properly caught the condition, and it does.)
CountRound (Score:1)
Re: (Score:1)
main program (Score:1)
Unlike the others this is untested.
Re: (Score:1)