Randomizer //JavaScript Repository

Description

Container able to return itens based on probability, randomized and sequentially.
Created: 2005.08.08

Code (Download)

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/randomizer [rev. #1]

Randomizer = function(type){
    var o = this;
    (o.d = [], o.t = type || Randomizer.RANDOMIZED, o.x = -1, o.u = 0);
};
with({o: Randomizer, p: Randomizer.prototype}){
    o.SEQUENCED = (o.PROBABILITY = (o.RANDOMIZED = 0) + 1) + 1;
    p.add = function(object, probability){
        this.u += (this.d[ this.d.length ] = {o: object, p: Math.abs(probability || 1)}).p;
    };
    p.remove = function(index){
        index > -1 && index < this.d.length && (this.u -= this.d.splice(index, 1).p);
    };
    p.next = function(){
        if(!this.u)
            return null;
        var i = 0, m = 0, x = this.t == Randomizer.SEQUENCED ?
            (this.x = (this.x + 1) % this.d.length)
            : Math.round(Math.random() * (this.t == Randomizer.PROBABILITY ? this.u
            : this.d.length - 1));
        if(this.t == Randomizer.PROBABILITY)
            do m += this.d[ i++ ].p;
            while(x > m || !((x = --i) + 1));
        return this.d[ x ].o;
    };
}

Example (Example)

<script type="text/javascript">
//<![CDATA[

var probability = new Randomizer(Randomizer.PROBABILITY);
probability.add("A", 20);
probability.add("B", 10);
probability.add("C", 2);

document.write("<h2>Randomizer.PROBABILITY = A: 20, B: 10, C: 2</h2>");
for(var i = 20; i--; document.write(probability.next(), ", "));

var random = new Randomizer(Randomizer.RANDOMIZED);
random.add("A");
random.add("B");
random.add("C");

document.write("<h2>Randomizer.RANDOMIZED = A, B, C</h2>");
for(var i = 20; i--; document.write(random.next(), ", "));


var sequenced = new Randomizer(Randomizer.SEQUENCED);
sequenced.add("A");
sequenced.add("B");
sequenced.add("C");

document.write("<h2>Randomizer.SEQUENCED = A, B, C</h2>");
for(var i = 20; i--; document.write(sequenced.next(), ", "));

//]]>
</script>

Help

Constructor

Randomizer(type: RandomizerType)
Generates an instance of Randomizer.
type
adjusts the container behaviour, the possible values are: Randomizer.SEQUENCED (returns items in the same order they were inserted), Randomizer.PROBABILITY (returns items randomically, but taking in consideration the probability defined for each one) and Randomizer.RANDOMIZED (returns items randomically)

Methods

Randomizer.add(object: Object, probability: Integer): void
Adds an item to the container.
object
object that will be added
probability
useful only when the container type is "Randomizer.PROBABILITY", where "probability" must be an integer number positive and higher than 1
Randomizer.remove(index: Integer): void
Removes an element from the container.
index
index of the element
Randomizer.next(void): Object
Returns an item based on the container type.

Rank (Votes: 11)

3.73