Jump to content

Random Statements


Tura

Recommended Posts

I couldn't find how to make over two random statements. I tried codes like this:

<script type="text/javascript">var r=Math.random()if (r>0.5) {document.write("(one)")}if(r=1){document.write("(two)")}else{document.write("(three)")}</script>

But that didn't work. Is there a way to make over two random statements so that they all appear with about the same % chance?

Link to comment
Share on other sites

Tura,I'm not sure exactly how you want the outcome calculated.This example breaks the random number down to "thirds"( .33 )

    function mkRandom(){    var r = Math.random();      switch (true){        case(r < .33):          alert('First');          break;        case(r < .66):          alert('Middle');          break;        default:          alert('Last');          break;      }    }

Let us know if you have any questions, :)

Link to comment
Share on other sites

Tura,I'm not sure exactly how you want the outcome calculated.This example breaks the random number down to "thirds"( .33 )
    function mkRandom(){    var r = Math.random();      switch (true){        case(r < .33):          alert('First');          break;        case(r < .66):          alert('Middle');          break;        default:          alert('Last');          break;      }    }

Let us know if you have any questions, :)

I don't think that switch statement will work, because you have to compare upwards and downwards. If the Math.random is .25, it will be true for both < .33 and <.66
Link to comment
Share on other sites

While I tested the original code in IE, FF and Opera, I agree with Jonas that it will be a better model if we adjust our tests.

<html>  <head>  <title></title>  </head>  <body>  <script type="text/javascript">  function mkRandom(){       var r = Math.random();     switch (true){       case(r <= .33):         document.write('One');         break;       case(r > .33 && r <= .66):         document.write('Two');         break;       default:         document.write('Three');         break;     }  }  mkRandom();  </script>  </body></html>

Thanks, :)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...