fieldkit
Version:
Basic building blocks for computational design projects. Written in CoffeeScript for browser and server environments.
106 lines (85 loc) • 2.53 kB
JavaScript
// Generated by CoffeeScript 1.6.3
/*
Random based on Jon Watte's mersenne twister package.
Adds several utility methods under a unified interface, that'll allow to use
different number generators at some point.
*/
(function() {
var Random, mersenne, util;
mersenne = require('mersenne');
util = require('../util');
Random = (function() {
function Random(initialSeed) {
if (initialSeed == null) {
initialSeed = 0;
}
this.seed(initialSeed);
}
Random.prototype.seed = function(value) {
this.seedValue = value;
return mersenne.seed(this.seedValue);
};
Random.prototype.toString = function() {
return "Random(" + this.seedValue + ")";
};
Random.prototype.random = function() {
var k;
k = 1000000;
return mersenne.rand(k) / k;
};
Random.prototype.randi = function(min, max) {
return Math.floor(this.random() * (max - min) + min);
};
Random.prototype.randf = function(min, max) {
return this.random() * (max - min) + min;
};
Random.prototype.randn = function() {
return this.random() * 2 - 1;
};
Random.prototype.flipCoin = function(chance) {
if (chance == null) {
chance = 0.5;
}
return this.random() < chance;
};
Random.prototype.shuffle = function(list) {
return list.sort(function() {
return 0.5 - this.random();
});
};
Random.prototype.pick = function(list, count) {
var i, indices, result, _i, _j, _ref;
if (count == null) {
count = 1;
}
switch (list.length) {
case 0:
return null;
case 1:
return list[0];
default:
if (count === 1) {
return list[this.randi(0, list.length)];
} else {
indices = [];
for (i = _i = 0, _ref = list.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
indices.push(i);
}
util.shuffle(indices);
result = [];
for (i = _j = 0; 0 <= count ? _j < count : _j > count; i = 0 <= count ? ++_j : --_j) {
result.push(list[indices[i]]);
}
return result;
}
}
};
Random.prototype.pickAB = function(listA, listB, chance) {
var list;
list = this.next() < chance ? listA : listB;
return this.pick(list);
};
return Random;
})();
module.exports.Random = Random;
}).call(this);