Click to See Complete Forum and Search --> : Array Problem (semi-easy problem)


petermar30030
06-26-2003, 05:42 PM
I Need To Know A little About Arrays and The Math.random() function So That I Can Create a Program That Will Give Random Messages such as 'Good Things Happen To Good People.' and 'You Can Think Much Clearer On a Calm Mind.'
If Some-one can make A Sample Program Dealing With Arrays So That I Might Be Able To Learn From Them, I'd Really Appreciate it.
P.S
Please Comment Lots If You Do Make A Sample Program...:cool:

Charles
06-26-2003, 06:15 PM
<script type="text/javascript">
<!--
Array.prototype.random = function () {return this[Math.round (Math.random() * Math.ceil (this.length / 10) * 10) % this.length]}

alert(['fee', 'fie', 'foe', 'fum'].random());
// -->
</script>

Charles
06-26-2003, 06:58 PM
The idea there is to create for all members of the Array class a method that returns a random element of that particular Array. We would call the method with Array.random() where "Array" is some Array.

Array.prototype.random = function () {return this[n]}

Would do just that, if n is some random number between 0 and Array.length - 1. The tricky part is getting n. x % y returns the remainder when x is divided by y so m % Array.length would give you the desired random number if m had one more diget than Array.length. The problem is that Math.random() returns a number between 0 and 1. So we take the length of the Array, divide it by ten and round up to get the number of necessary digits and then we multiply our random number by that and by ten. Lastly we round off the whole thing because Array indices are whole numbers.

petermar30030
06-26-2003, 07:51 PM
Thanks Alot Charels, You Are A Brilliant Person!:cool: