1 Algorithm for random numbers [Web Developing] 9th March 2011, 11:38 am
alt.332
Administrator
Hello everybody, I want to share some algorithm for js but it's also useful for other programming languages.... This one is not my own idea. I got this one when I read js programming for absolute beginner(e-book)... It's useful when u want random numbers in certain range....
eg - random number between 1-6 , 4-20, 10-100, etc....
Very simple.
1. Get a random floating point value.
2. Multiply the value by high.
3. Convert the value to integer.
4. Add the value of low.
Example, we want to make some dice program.... The lowest number is 1 & highest is 6...
1st Step - make random floating point value,
eg - var randomNum = Math.random();
2nd Step - multiply with high,
eg - var high = randomNum * 6;
3rd Step - convert the value to integer,
eg - var integer = Math.floor(high);
Last one 4th Step - add the value of low,
eg - var result = integer + 1;
that's all.... it's very simple & very useful.....
here's the sample code...
eg - random number between 1-6 , 4-20, 10-100, etc....
Very simple.
1. Get a random floating point value.
2. Multiply the value by high.
3. Convert the value to integer.
4. Add the value of low.
Example, we want to make some dice program.... The lowest number is 1 & highest is 6...
1st Step - make random floating point value,
eg - var randomNum = Math.random();
2nd Step - multiply with high,
eg - var high = randomNum * 6;
3rd Step - convert the value to integer,
eg - var integer = Math.floor(high);
Last one 4th Step - add the value of low,
eg - var result = integer + 1;
that's all.... it's very simple & very useful.....
here's the sample code...
- Code:
<html>
<head>
<title>JS Practice</title>
</head>
<body>
<script>
var rollraw = 0;
var rollBigger = 0;
var rollnt = 0;
var rollFinal = "";
rollraw = Math.random();
rollBigger = rollraw * 6;
rollint = Math.floor(rollBigger);
rollFinal = rollint + 1;
alert("Your number is: " + rollFinal);
</script>
</body>
</html>