Solved

# Print Only First Three Highest Values

Posted on 2007-11-16
185 Views
Hi All

I have 8 variables with numeric values:

\$Variable1 = 80;
\$Variable2 = 50;
\$Variable3 = 30;
\$Variable4 = 70;
\$Variable5 = 20;
\$Variable6 = 50;
\$Variable7 = 40;
\$variable8 = 10;

How can I print only the first three with the highest value.

EX:

print "\$Variable1\n \$Variable4\n \$Variable2\n";
0
Question by:blnukem
• 2
• 2

LVL 3

Expert Comment

It is better to store them in an array I think

@array = (80, 50, 30, 70, 20, 50, 40, 10);
@sorted = sort { \$b <=> \$a } @array;

the highest number is now stored at index 0
print "highest: ", \$sorted[0], "\n";
print "second highest: ", \$sorted[1], "\n";
...

remarkt that if you do {\$a <=> \$b}, you sort in an ascending way.
with the current {\$b <=> \$a}, you sort in a descending way
0

LVL 84

Accepted Solution

ozo earned 500 total points
print "\$_\n" for (sort \$Variable1,\$Variable2,\$Variable3,\$Variable4,\$Variable5,\$Variable6,\$Variable7,\$Variable8)[-3..-1]
0

Author Closing Comment

Thanks ozo!!
0

LVL 3

Expert Comment

@ozo,

the sort function - as far as I know, sorts alphabetically, and your solution will run into problems.
But if you change e.g. \$variable8=10 into \$variable8=150, your code will still return 50, 70, 80 because it sorts them alphabetically
same problem if you change variable8 from 10 to 9: your solution will then return 9 as the highest number (higher than 80).
0

LVL 84

Expert Comment

> sorts alphabetically
true
(sort {\$b<=>\$a} \$Variable1,\$Variable2,\$Variable3,\$Variable4,\$Variable5,\$Variable6,\$Variable7,\$Variable8)[0..2]
would have been better
0

## Featured Post

This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
This article will show, step by step, how to integrate R code into a R Sweave document
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …