home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!sun-barr!ames!uakari.primate.wisc.edu!caen!malgudi.oar.net!uoft02.utoledo.edu!jupiter!steiner
- From: steiner@jupiter.cse.utoledo.edu (jason "Think!" steiner)
- Newsgroups: comp.lang.perl
- Subject: Re: Ordering indices based on their values
- Message-ID: <1992Aug26.203033.9718@uoft02.utoledo.edu>
- Date: 27 Aug 92 01:30:32 GMT
- References: <GLENN.92Aug26122420@capella.clsi.COM>
- Distribution: comp.lang.perl
- Lines: 61
- Nntp-Posting-Host: jupiter.cse.utoledo.edu
-
- glenn@clsi.COM (Glenn Boysko) writes:
- >
- > Hello Perl Hackers,
- >
- > I was wondering if anyone knew of an efficient, simple way to
- > produce an ordered array of indices whose order was based on their
- > values. Consider the following array:
- >
- > Index | Value
- > ------+------
- > 0 | 7
- > 1 | 2
- > 2 | 4
- > 3 | -1
- > 4 | 5
- >
- > I would like a new array whose values are indices of the input
- > array. The values of the new array are ordered such that their
- > values in the original array are ordered in descending order. The
- > resulting array for our example is:
- >
- > Index | Value
- > ------+------
- > 0 | 0
- > 1 | 4
- > 2 | 2
- > 3 | 1
- > 4 | 3
- >
- > Note that an appropriate solution would be to use an associative
- > array to store (value, index) entries and then sort the keys.
- > However, this will not work if the values of the original array are
- > not distinct.
- >
- > Once this array has been generated, I can process each entry in the
- > orignal array according to the descending order of the values.
- >
- > Any Ideas?
- > Glenn
-
- here's how i would do it...
-
- #!/usr/local/extras/bin/perl
-
- @array=(7,2,4,-1,5);
- @index=(0,1,2,3,4);
-
- @index = sort {$array[$b]<=>$array[$a];} @index;
- for (@index) { print "$_\t$array[$_]\n"; }
-
- and it works if elements are not distinct.
-
- jason "am i a Perl hacker now?" steiner
-
- --
- `,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`
- `,` Do you happen to be of the mechanical persuasion? `,`
- `,` Don't be taken in / by weak imitations. `,`
- `,` A robot and a man got the same limitations. `,`
- `,` -- Rise Robots Rise `,`
- `,`,`,`,`,`,` steiner@jupiter.cse.utoledo.edu `,`,`,`,`,`
-