This code is supposed to create an array that has enough entries to add
up to 10000 using an Array of numbers. The middle numbers in the Array
are weighted towards the middle.
function Random(x) { return Math.floor(x*Math.random()) }
myArray = [4,4.25,4.5,4.75,5,5.25,5.25,
5.5,5.5,5.75,5.75,6,6,6.25,
6.25,6.5,6.5,6.75,6.75,7,7,
7.25,7.25,7.5,7.5,7.75,7.75,
8,8,8.25,8.5,8.75,9]
maxTotal = 10000;
k = 0;
r = 0;
document.write('newArray = [')
while (k <= maxTotal){
var currentBoard = Random(33)
document.write(myArray[currentBoard] + ',')
k = k+currentBoard
r++
}
document.write('0];')
//document.write('<br>' + k)
//The above line was to make sure I was getting
//the maxTotal.
//The goal is to be able to create a random array
//where the elements of the array add up to maxTotal
//or over 10000 by one element.
If I uncomment the document.write line I am getting a number just larger
than maxTotal. Perfectly acceptable. Then, if I take the array it
creates and copy/paste it into a new file, then loop through the array
adding entries I don't get the same result.
newArray = [........];
r = 0;
for (i=0;i<newArray.length;i++){
r = r + newArray[i]
}
document.write(r)
What I expected to get would be the same results as k in the first
document.write statement but I don't. It is 5:30AM and my eyes are
crossed trying to find what I am missing that explains why they aren't
adding up the same...
If someone will kindly point out what I am missing I will probably think
"Geez, Randy, you are stupid for missing that" but I would be grateful
for the answer.
--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/