Howdy, Stranger!

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

organize set variables based on value

Ok so i have a set of randomly generated variables similar to: <<set $1 to random(3,27)>> <<set $2 to random(3,27)>> etc. etc.

As these random numbers are generated I want to organize them and have them set to other variables such as : Highest number between $1 and $1 gets Set to $firstplace, or maybe something along the lines of <<set $firstplace to highest of $1 & $2>>

Clearly Im a bit out of my depth and just cannot formulate a way to do this properly. Any help would be appreciated.

Thanks.

Comments

  • You need to state which Story Format you are using when you ask a question, as answers can be different for each one. Based on the syntax of the examples used in your question I am going to assume you are using SugarCube 1.0.34

    There are a number of different ways you can do what you want, which you use depends on what you are actually trying to achieve.

    1. Find the maximum from a set of number values.

    You can use the Javascript Math.max() function to this, the code would look something like the following:
    note: variable names should start with a letter, so I have changed the ones from your example.
    <<set $v1 to random(3,27)>> <<set $v2 to random(3,27)>>
    <<set $firstplace to Math.max($v1, $v2)>>
    firstplace: $firstplace
    

    2. Sort a set of numbers from highest to lowest.

    You can place your numbers into an array and then use a combination of the Javascript sort() method and the reverse() method to order the numbers:
    <<set $list to []>>
    <<set $list.push(random(3,27))>>
    <<set $list.push(random(3,27))>>
    <<set $list.push(random(3,27))>>
    
    <<set $sorted to $list.sort().reverse()>>
    <<set $firstplace to $list[0]>>
    <<set $secondplace to $list[1]>>
    <<set $thirdplace to $list[2]>>
    firstplace: $firstplace
    secondplace: $secondplace
    thirdplace: $thirdplace
    
    notes:
    a. The first element in an array has an index of zero not one.
    b. It is possible to do the highest to lowest sorting just using the only sort() method but that would require me to explain what a Compare Function is.
Sign In or Register to comment.