prng4.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // AMD-ID "dojox/math/random/prng4"
  2. define("dojox/math/random/prng4", ["dojo", "dojox"], function(dojo, dojox) {
  3. dojo.getObject("math.random.prng4", true, dojox);
  4. // Copyright (c) 2005 Tom Wu
  5. // All Rights Reserved.
  6. // See "LICENSE-BigInteger" for details.
  7. // prng4.js - uses Arcfour as a PRNG
  8. function Arcfour() {
  9. this.i = 0;
  10. this.j = 0;
  11. this.S = new Array(256);
  12. }
  13. dojo.extend(Arcfour, {
  14. init: function(key){
  15. // summary:
  16. // Initialize arcfour context
  17. // key: Array:
  18. // an array of ints, each from [0..255]
  19. var i, j, t, S = this.S, len = key.length;
  20. for(i = 0; i < 256; ++i){
  21. S[i] = i;
  22. }
  23. j = 0;
  24. for(i = 0; i < 256; ++i){
  25. j = (j + S[i] + key[i % len]) & 255;
  26. t = S[i];
  27. S[i] = S[j];
  28. S[j] = t;
  29. }
  30. this.i = 0;
  31. this.j = 0;
  32. },
  33. next: function(){
  34. var t, i, j, S = this.S;
  35. this.i = i = (this.i + 1) & 255;
  36. this.j = j = (this.j + S[i]) & 255;
  37. t = S[i];
  38. S[i] = S[j];
  39. S[j] = t;
  40. return S[(t + S[i]) & 255];
  41. }
  42. });
  43. dojox.math.random.prng4 = function(){
  44. return new Arcfour();
  45. };
  46. // Pool size must be a multiple of 4 and greater than 32.
  47. // An array of bytes the size of the pool will be passed to init()
  48. dojox.math.random.prng4.size = 256;
  49. return dojox.math.random.prng4;
  50. });