Sorting Arrays
Michael Fowler
michael at shoebox.net
Tue Sep 28 17:28:43 CDT 1999
I'm going to attempt an answer, but I was somewhat confused by the
terminology and syntax used at points.
On Tue, Sep 28, 1999 at 06:27:21AM -0800, Kevin J Creason wrote:
> @canlist @tvote
These are what I assume you're trying to sort for.
> @district{$c,$vc} and $subvote{$c,$vc}
This implies that %district is a hash, and you're pulling multiple keys out
at once. From the syntax, %subvote is a hash, and you're looking up the key
"$c$;$vc", $; being the subscript seperator (perldoc perlvar).
> Here is my dilemma: I want to sort my @canlist and tvote by
> tvote, so that highest vote getters are listed on top instead
> of alphabetically. I'm sure there is a way, I just haven't
> found it yet, but I also have to keep the other arrays in
> sync.
>From this I'm going to assume you have two arrays, @canlist and @tvote.
Each element in @canlist has a corresponding element in @tvote, at the same
array index. Here is my suggestion for sorting this:
@index = sort { $tvote[$b] <=> $tvote[$a] } (0 .. $#tvote);
Now @index contains the array indexes in @canlist and @tvote that correspond
to the highest vote-getter to the least. E.g. $canlist[$index[0]] will give
you the candidate with the highest number of votes, $canlist[$index[-1]]
will give you the candidate with the least number of votes.
A solution that would probably be easier to deal with is to integrate your
lists together into a hash:
%candidates = map { $canlist[$_], $tvote[$_] } (0 .. $#canlist);
Now, sort the candidates by votes:
@keys = sort { $candidates{$b} <=> $candidates{$a} } keys(%candidates);
Now @keys contains the candidates' names from highest vote-getter to least.
E.g. $keys[0] is the name of your highest vote-getter, $keys[-1] is the name
of the lowest vote-getter. The number of votes for a given candidate can be
retrieved by lookup up the candidate's name in the hash,
$candidate{$keys[0]} for your highest vote-getter's votes.
Hopefully that helps a bit.
Michael
--
There isn't a mome rath alive that can outgrabe me.
--
=================================================
Mailing list info: If at any time you wish to (un|re)subscribe to
the list send the request to majordomo at hfb.pm.org. All requests
should be in the body, and look like such
subscribe anchorage-pm-list
unsubscribe anchorage-pm-list
More information about the Anchorage-pm
mailing list