Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

How to print the highest variable?

I have a bunch of variables and want to print the one with the highest number.  Example:

$variable1 = 2
$variable2 = 7
$variable3 = 4

it would print $variable2 because it's the highest.

Comments

  • Use the javascript Math.max() function:
    <<print Math.max($variable1, $variable2, $variable3)>>
  • greyelf wrote:

    Use the javascript Math.max() function:
    <<print Math.max($variable1, $variable2, $variable3)>>

    what about if I want the variable with the highest number to show the variable name instead of the number like:
    $red = 2
    $blue = 1
    $green = 3
    and I want it to say green instead of 3?  Or place it in an if statement like: if math.max is $red print red is the highest?
  • To do this I would replace the individual variables with an associated array (also know as an object in java-script) and do the following:

    NOTE:
    a. The passages below are in TWEE format.
    b. If two or more of the counters have the same value then the highestColour() function will return the first one found with that value.

    1. Setup the default value for the colour counters.

    :: StoryInit

    <<set $colours to {red: 0, blue: 0, green: 0}>>
    2. Create a Script Passage to store the java-script used to determine the highest colour.

    :: HighestColour Script [script]

    if ('function' != typeof window.highestColour) {
    window.highestColour = function (colours) {
    var highestColour = null;
    var value = 0;
    for (var colour in colours) {
    if (highestColour === null || value < colours[colour]) {
    highestColour = colour;
    value = colours[colour];
    }
    }
    return highestColour;
    };
    }
    3. Add some code to increment the counters,  print their values, and determine which colour has the highest value

    :: Start

    Increment the colour counters:
    <<set $colours.red += 2>>
    <<set $colours.blue += 7>>
    <<set $colours.green += 3>>

    Print out the current values:
    Red: <<print $colours.red>>
    Blue: <<print $colours.blue>>
    Green: <<print $colours.green>>

    Print out the name of the colour with the highest value:
    <<print highestColour($colours)>>
Sign In or Register to comment.