Fracture a Number

Actionscript:
  1. var target:Number = 1024;
  2. var slices:Array = [target];
  3. var leng:int = 11;
  4.  
  5. for (var i:int = 0; i<leng-1; i++){
  6.      var index:int = int(Math.random()*slices.length);
  7.      var val:Number = slices[index];
  8.      var rand:Number = Math.random() * val/2;
  9.      slices[index] = val - rand;
  10.      slices.push(rand);
  11. }
  12.  
  13. trace(slices);
  14.  
  15. // test that they all add up
  16. var sum:Number = 0;
  17. for (i = 0; i<slices.length; i++){
  18.     sum += slices[i];
  19. }
  20. 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

This entry was posted in arrays, misc and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*