Commits

Shlomi Fish  committed e182282

Implement MicrosoftRand shuffle.

There does not appear to be an easy way to swap two elements in JS:

http://stackoverflow.com/questions/872310/javascript-swap-array-elements .

  • Participants
  • Parent commits 3c3bc66

Comments (0)

Files changed (2)

File abc-path/js/abc-path-test.js

         // TEST
         equals (r.rand(), 6334, "3rd result for seed 1 is 6,334.");
     });
+
+    test("MicrosoftRand Shuffle", function() {
+        expect(2);
+
+        var r = new ABC_Path.MicrosoftRand({seed : 24 });
+
+        var myarr = [0,1,2,3,4,5,6,7,8,9];
+
+        var ret = r.shuffle(myarr);
+        // TEST
+        deepEqual(
+            myarr,
+            [1,7,9,8,4,5,3,2,0,6],
+            'Array was shuffled.'
+            );
+
+        // TEST
+        equals (ret, myarr, 'shuffle returns the same array.');
+    });
 }

File abc-path/js/abc-path.js

             this.setSeed((this.getSeed() * 214013 + 2531011) & 0x7FFFFFFF);
             return ((this.getSeed() >> 16) & 0x7fff);
         },
+        max_rand: function(mymax) {
+            return this.rand() % mymax;
+        },
+        shuffle: function(deck) {
+            if (deck.length) {
+                var i = deck.length;
+                while (--i) {
+                    var j = this.max_rand(i+1);
+                    var tmp = deck[i];
+                    deck[i] = deck[j];
+                    deck[j] = tmp;
+                }
+            }
+            return deck;
+        },
     },
 });