tags:

views:

80

answers:

5

If I have variables with numbers how to figure out which are the three with the highest value?

+7  A: 

You can either manually iterate through them and extract the top 3 (maintaining the information you have so far in some form) or just sort them all and take the top 3

Steve B.
+1  A: 

This really depends on the language you're using.

I would suggest putting them all in an array, sort them from highest to lowest, and then the first three elements would be your highest.

Bryan Ross
A: 

You may sort them in descending order and the first three will be the ones you want.

Mario Marinato -br-
A: 

Don't forget that there are a couple odd cases here:

  1. A case where the highest value occurs more than 3 times so that there isn't just one correct answer. For example, if there a dozen variables all with a value of zero.

  2. If you have less than 3 variables for such a program there could be a problem.

JB King
A: 

I don't want to say that I'm a newb, because I don't think I am. However this question was rather difficult to answer. I've only been coding PHP for around 8 months, and I imagine that there is a much better way of accomplishing such an effect. Based on my skill set I choose to use PHP and came up with this:

<?php

$variable = array();
$variable[1] = 15;
$variable[2] = 30;
$variable[3] = 9;
$variable[4] = 86;
$variable[5] = 46;
$variable[6] = 12;
$variable[7] = 86;

## Clean the array of duplicates
$variable = array_unique($variable);

## Sort array from greatest to lease in DESC order
rsort($variable);


for ($i = 0; $i < 3; $i++):
    echo $variable[$i]."<br />";
endfor;

?>

The breakdown

  • First declare your array
  • Then your array items
  • Clean the array with "array_unique" to remove reiterated values
  • Use "rsort" to sort array from greatest to least
  • Initiate a for loop in which $i equals 0, run only while $i is less then 3, add one to $i for each iteration
  • Echo the array item

Good luck!

David