Fracture a Number

var target:Number = 1024;
var slices:Array = [target];
var leng:int = 11;

for (var i:int = 0; i<leng-1; i++){
	 var index:int = int(Math.random()*slices.length);
	 var val:Number = slices[index];
	 var rand:Number = Math.random() * val/2;
	 slices[index] = val - rand;
	 slices.push(rand);
}

trace(slices);

// test that they all add up
var sum:Number = 0;
for (i = 0; i<slices.length; i++){
	sum += slices[i];
}
trace("test that they all add up: ", sum);

The above snippet creates an array of a specified length whose elements all add up to the variable target. Here is some example output:


165.31133050055192,322.23456030456015,
257.47582363389245,26.9984893942173,1.96283924962002,
5.466277873168191,21.362282634705164,62.68168197512457,
76.63028224500404,36.27274381401516,12.558309228795265,35.04537914634583
test that they all add up: 1024

Leave a Reply

Your email address will not be published. Required fields are marked *