Sorting Arrays

Kevin Creason kevinc at gci.net
Wed Sep 29 00:47:37 CDT 1999


Thank you (Michael, Arthur, and Leif for thinking about it anyway) for the
answers... I will start monkeying tomorrow and try to get back to the group
with some feedback or clarification.


-----Original Message-----
From: Michael Fowler <michael at shoebox.net>
To: Kevin J Creason <kevinc at gci.net>
Cc: Anchorage Perl Mongers <anchorage-pm-list at happyfunball.pm.org>
Date: Tuesday, September 28, 1999 2:28 PM
Subject: Re: Sorting Arrays


>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