in reply to Re: Challenge: A malicious election
in thread Challenge: A malicious election
What it does wrong:use strict; use warnings; my @candidates = qw( Alice Bob ); ## initialize each candidate with 0 votes my %votes; @votes{map lc, @candidates} = ( [0] ) x @candidates; print "Available candidates: @candidates\n"; print "To cast a vote, type candidate's name. End the election with ^D +\n"; ## record the input vote while (<>) { chomp( my $vote = lc $_ ); if ( exists $votes{$vote} ) { $votes{$vote}[0]++; } else { warn "Invalid candidate!\n"; } } ## print all votes print "Final results:\n"; printf "%10s : %d\n", $_, $votes{lc $_}[0] for @candidates;
What would be much nicer is if there is some way to sneak in a division-by-two on the votes, so there will always be the right number of votes (or one less). Perhaps someone can think of a way to sneak >>=1 in there? Or some cleverness in the printf template?
I also think that since having the extra array ref in there is suspicious, one could try to store extra data in the array @{ $votes{$candidate} }. I couldn't think of anything very convincing though.
blokhead
|
|---|