Forum Moderators: open

Message Too Old, No Replies

"freezing" output of math.random()

impossible?

         

ctoz

8:36 pm on Dec 3, 2007 (gmt 0)

10+ Year Member



Here's a function using math.random:

function Coin1() {
var m = Math.random()
if (m < 0.5) return 2; else return 3 }

Is it possible to to take the 2 or 3, and have these return the words "tails" for 2 and "heads" for 3?

Both of these functions


function numtoHT1() {
if (Coin1() == 3){
return "heads";
}else{
return "tails"; }}

and
 
function numtoHT2() {
return (Coin2() == 3)? "heads" : "tails" }

actually run the math.random() function afresh to generate the output, they don't store the output of invoking the function first time round. Run this test page a few times to illustrate:

< Sorry, no links to test pages >

I'm beginning to think it's not possible.

[edited by: tedster at 9:07 pm (utc) on Dec. 3, 2007]

Fotiman

9:11 pm on Dec 3, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I don't understand what you're asking.


Is it possible to to take the 2 or 3, and have these return the words "tails" for 2 and "heads" for 3?

You're already doing that... so I'm not sure why you ask the question.


actually run the math.random() function afresh to generate the output, they don't store the output of invoking the function first time round

Of course, that's the way you've coded it.


I'm beginning to think it's not possible.

What's not possible?

ctoz

11:57 pm on Dec 3, 2007 (gmt 0)

10+ Year Member



Sorry if it's badly-expressed. Never mind.

I should have been more patient on another board, and allowed the folks there to get some sleep... before spelling out a solution for me:

< no links to test pages, please >

where 3 always returns "heads" and 2 always returns "tails"; which is not the case with test.htm.

[edited by: tedster at 1:22 am (utc) on Dec. 4, 2007]

Dabrowski

11:29 am on Dec 4, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Sorry if it's badly-expressed. Never mind.

Not badly expressed, just badly coded. Try this....

function flip() { 
return (Math.random <0.5? "tails": "heads");
}

That should return heads and tails for you.