开发者

simple logic question comparing variables

If I开发者_运维技巧 have variables with numbers how to figure out which are the three with the highest value?


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


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!


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜