本文介绍了模拟加权随机数 - Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了多篇堆栈溢出文章,但找不到合理的回复.如有重复请注明.

I looked at multiple stack overflow articles and couldn't find a reasonable response. If there is a duplicate please indicate.

我有一个物品清单.类似的东西:

I have a list of items. Something like:

String GiantRat []={"Bandage", "Healing Potion", "Minor Healing Potion", "Rat Teeth", "Fur", "Rat Tail", ""};

这表示此giantRat 可能掉落的物品.

This indicates the possible items this giantRat can drop.

有一个具有匹配索引的相关数组,其中包含我希望发生的加权概率.类似的东西:

There is a correlated array with matching index that holds what I would hope is the weighted probability of the occurence. Something like:

int GiantRatDropRate[]={1,1,1,6,8,3,5};

这些将被放大到 50(每个乘以 2),然后理论上我会扮演一个 50 面骰子(Random).这似乎是错误的方法,我想不出办法做到这一点.

These would be scaled up to say, 50 (multiplied each by 2) and then I would theoretically role a 50 sided dice (Random). This seems like it's been the wrong approach and I can't figure out a way to do this.

同样,我们的想法是掷骰子并根据权重从列表中选择 1 个项目.也许掷骰子的方式是错误的.任何帮助表示赞赏.

Again, the idea is to roll a die and choose 1 item from the list based on weighting. Maybe the dice roll is the wrong way. Any help appreciated.

推荐答案

一个简单的方法如下.不需要*2,因为概率是一样的.

A simple approach could be as follows. No need to *2, because probabilities will be the same.

    String giantRat []={"Bandage", "Healing Potion", "Minor Healing Potion", "Rat Teeth", "Fur", "Rat Tail", ""};


    int[] a = {1,1,1,6,8,3,5};
    int sum = 0;
    for(int i: a)
       sum += i;
    Random r = new Random();
    int s = r.nextInt(sum);  //Get selection position (not array index)

    //Find position in the array:
    int prev_value = 0;
    int current_max_value = 0;
    int found_index = -1;
    for(int i=0; i< a.length; i++){ //walk through the array
      current_max_value = prev_value + a[i];
      //is between beginning and end of this array index?
      boolean found = (s >= prev_value && s < current_max_value)? true : false;
      if( found ){
        found_index = i;
        break;
      }
      prev_value = current_max_value;
    }

    String selection = "unknown";
    if( found_index != -1 ){
      selection = giantRat[found_index];
    }
    System.out.println(selection);

http://ideone.com/xyQlvN

这篇关于模拟加权随机数 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 08:59