如何从Perl中的数组获取加权随机选择? [英] How can I get weighted random selections from an array in Perl?

查看:111
本文介绍了如何从Perl中的数组获取加权随机选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从数组中随机抽取一些元素.我通过随机化索引$array[int(rand(100))]来做到这一点.我希望某些元素出现得更频繁.我该怎么办?

I need to random some elements from an array. I'm doing that by randomizing the index $array[int(rand(100))]. I want some of the elements to appear more often. How do I do it?

我想到了一个愚蠢的解决方案,即将这些元素在数组中重复几次,但是我敢肯定你们可以做得更好.

I thought of a stupid solution of having those elements duplicated several times in the array, but I'm sure you guys can do better.

推荐答案

此sub'得到一个元素和权重数组-A(10)B(30)C(5)-,并根据重量.

this sub' gets an array of element and weight -A(10)B(30)C(5)-and random one of the elements according the the weights.

sub we_rand {

sub we_rand {

my $line=$_[0];#get the elements array
my @b = split(/\(\d+\)/,$line);#b now holds each elemnet from the array
my @a = "";
my $i=0;
my $tmp;
    while ($line=~m/(\(\d+\)+)/g) {
        $tmp=$1;#temp gets the weight
        if ($tmp=~m/\d+/g) {
            if ($i>0){
            $a[$i]=$&+$a[$i-1];#if weight is grather then 0 -each cell of
            #a sums up the wheights up to it 
            }
            else {
            $a[$i]=$&;
            }
        }
        $i++;
         }
        if ($i>1){
            my $n=int(rand($a[$i-1])+1);#rand a number in the boundries of
            #the total weight of all the elements
            my $s=scalar(@b);
            #go through a and compare to the randomized num-then take the
            #element from b
            for ( $i=0;$i<scalar(@b);$i++){
                if($n<=$a[$i])
                {
                    $c=$b[$i];
                last;
                    }
            }
        } else {
        $c=$b[0];#if only one element
        }

        return $c;

}

您这样称呼sub':

}

you call the sub' like this:

my $ rand = we_rand(A(10)B(30)C(5)D(17)); -#$ rand = B

my $rand=we_rand(A(10)B(30)C(5)D(17)); -#$rand=B

这篇关于如何从Perl中的数组获取加权随机选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆