home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #19 / NN_1992_19.iso / spool / comp / lang / perl / 5523 < prev    next >
Encoding:
Internet Message Format  |  1992-08-26  |  2.1 KB

  1. Path: sparky!uunet!sun-barr!ames!uakari.primate.wisc.edu!caen!malgudi.oar.net!uoft02.utoledo.edu!jupiter!steiner
  2. From: steiner@jupiter.cse.utoledo.edu (jason "Think!" steiner)
  3. Newsgroups: comp.lang.perl
  4. Subject: Re: Ordering indices based on their values
  5. Message-ID: <1992Aug26.203033.9718@uoft02.utoledo.edu>
  6. Date: 27 Aug 92 01:30:32 GMT
  7. References: <GLENN.92Aug26122420@capella.clsi.COM>
  8. Distribution: comp.lang.perl
  9. Lines: 61
  10. Nntp-Posting-Host: jupiter.cse.utoledo.edu
  11.  
  12. glenn@clsi.COM (Glenn Boysko) writes:
  13. > Hello Perl Hackers,
  14. > I was wondering if anyone knew of an efficient, simple way to 
  15. > produce an ordered array of indices whose order was based on their 
  16. > values.  Consider the following array:
  17. >     Index | Value
  18. >     ------+------
  19. >       0   |  7
  20. >       1   |  2
  21. >       2   |  4
  22. >       3   | -1
  23. >       4   |  5
  24. > I would like a new array whose values are indices of the input 
  25. > array.  The values of the new array are ordered such that their 
  26. > values in the original array are ordered in descending order.  The 
  27. > resulting array for our example is:
  28. >     Index | Value
  29. >     ------+------
  30. >       0   |  0
  31. >       1   |  4
  32. >       2   |  2
  33. >       3   |  1
  34. >       4   |  3
  35. > Note that an appropriate solution would be to use an associative 
  36. > array to store (value, index) entries and then sort the keys.  
  37. > However, this will not work if the values of the original array are 
  38. > not distinct.
  39. > Once this array has been generated, I can process each entry in the 
  40. > orignal array according to the descending order of the values.
  41. > Any Ideas?
  42. > Glenn
  43.  
  44. here's how i would do it...
  45.  
  46. #!/usr/local/extras/bin/perl
  47.  
  48. @array=(7,2,4,-1,5);
  49. @index=(0,1,2,3,4);
  50.  
  51. @index = sort {$array[$b]<=>$array[$a];} @index;
  52. for (@index) { print "$_\t$array[$_]\n"; }
  53.  
  54. and it works if elements are not distinct.
  55.  
  56. jason "am i a Perl hacker now?" steiner
  57.  
  58. --
  59. `,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`,`
  60. `,` Do you happen to be of the mechanical persuasion? `,`
  61. `,`      Don't be taken in / by weak imitations.      `,`
  62. `,`    A robot and a man got the same limitations.    `,`
  63. `,`                -- Rise Robots Rise                `,`
  64. `,`,`,`,`,`,` steiner@jupiter.cse.utoledo.edu `,`,`,`,`,`
  65.