[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

[FWP] Probabilistic selection



I have a specification of link destinations and their weighted
probabilities like so:

	my %target = (
    		'/:           _top'    => 1,
    		'index.amyl:  _parent' => 3,
    		'index.amyl:  _self'   => 15,
    		'upload.amyl: _parent' => 1,
	);

In other words, you go to index.amyl in target="_parent" with
probability 3 out of (1+3+15+1). The advantage of this scheme
is that you don't have to make anything add up to 1.0 or use
floating point, etc.

I implemented this fairly straightforwardly as follows,

    my $sum = 0; $sum += $_ for values %target;
    my $which = rand $sum;
    my $where;
    $sum = 0;
    for my $href (keys %target) {
        if ($which < ($sum += $target{$href})) { $where = $href; last }
    }

Any neater ways of doing this? Including perhaps, but not
limited to, a different probabilities specification. I.e. any
way of achieving the same goal.

Paul

PS This is running at http://amyl.org/

==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe