Non-repeated random numbers


/ Published in: ActionScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. // ************************************************** //
  2. // Author: ImHugo
  3. // URL: http://www.imhugo.com
  4. // ************************************************** //
  5.  
  6. // Vars
  7. var arrayToRandom:Array = new Array();
  8. var qRequired:Number = 5;
  9.  
  10. // Inserts Numbers in Array
  11. for(var i:Number = 1; i<=qRequired; i++)
  12. {
  13. arrayToRandom.push( i );
  14. }
  15.  
  16. // Outputs numbers non-repeated
  17. for(var k:Number = 1; k<=qRequired; k++)
  18. {
  19. // Search for value inside the Array in a random position
  20. var randomPos:Number = Math.floor( Math.random() * arrayToRandom.length );
  21.  
  22. // Selects value and removes it from Array
  23. var valueFromArray = arrayToRandom.splice(randomPos, 1);
  24.  
  25. // Converts value in number
  26. var numberRand = parseInt(valueFromArray);
  27.  
  28. trace(numberRand);
  29. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.