dongyuanguang3893 2018-02-16 12:52
浏览 275

根据该行的“权重”随机选择行

I have a table like this:

ID chance
1 1
2 2
3 4
4 1

Now I need to choose a rand() from this table

SELECT * FROM table
ORDER BY RAND()
LIMIT 1

But ID #2 has double the chances to be selected compared to ID #1 AND 4. Likewise ID #3 has four times the chances to be selected compared to ID #1 AND 4.

Somewhat similar to lottery based on chance.

  • 写回答

4条回答 默认 最新

  • dongnao6858 2018-02-16 13:26
    关注

    This is how lottery works in some of the games. Given table similar to your example (say, we also have chance column that indicated value-based possibility of getting this particular reward), the algorithm is:

    1. Calculate total lottery value (in your example it is 1 + 2 + 4 + 1 = 8).
    2. Generate a value that is from range 1..max (max is 8 in current example) inclusive.
    3. Iterate over all items from rewards list to find the one item where sum of all previous chances is more than generated number but less or equal than

    Say, we have generated number 5. Our comparison steps are:

    1. 0 < 5 <= (0) + 1 is false so ID1 is not what we get. Left side is 0 because we start our calculations from 0.
    2. 1 < 5 <= (1) + 2 is false so ID2 is not what we get.
    3. 1 + 2 < 5 <= (1 + 2) + 4 is true so we get ID3.

    Example in JavaScript:

    var rewards = [
      { id: 1, chance: 1 },
      { id: 2, chance: 2 },
      { id: 3, chance: 4 },
      { id: 4, chance: 1 }
    ];
    
    function getRandomInt(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    
    function generate() {
      var sum = 0;
      var next_sum = 0;
      var random = getRandomInt(1, rewards.reduce(function(pv, cv) {
        return pv + cv.chance;
      }, 0));
    
      for (var i = 0; i < rewards.length; i++) {
        next_sum = sum + rewards[i].chance;
        if ((random > sum) && (random <= next_sum)) {
          return rewards[i].id;
        }
        sum += rewards[i].chance;
      }
    }
    
    var winnerCounts = {}, i, winner;
    for (i = 0; i < 8000; i++) {
      winner = generate();
      winnerCounts[winner] = (winnerCounts[winner] || 0) + 1;
    }
    console.log("Number of times each id was selected after %d itrations", i);
    console.log(winnerCounts);

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接