按权重产生随机数

题目

实现一个抽奖功能。共有N中奖品,每种奖品都有一个对应的权重(整数),该奖品被抽到的概率与其权重成正比。假设奖品i的权重为weights[i],0 <= i < N,wieghts是长度为N的int数组,实现以下函数,返回抽中的奖品的编号。
举例:假设weights的内容为{10,20,20},那么应该有20%的概率返回0号奖品,40%的概率返回1号奖品,40%的概率返回2号奖品。
注:你可以使用的随机数相关的系统函数为int rand(int n),此函数返回值为[0,n)之间均匀分布的一个随机整数。
int randomByWeight(int[] weights)
{

}

代码

using System;

public class Test
{
    public static void Main()
    {
        int[] weights = new int[] { 5, 5, 3, 1 };
        int number = RandomByWeight(weights);
        Console.WriteLine("return prize is {0}", number);
    }

    public static int RandomByWeight(int[] weights)
    {
        for (int i = 1; i < weights.Length; i++)
        {
            weights[i] += weights[i - 1];
            Console.WriteLine("weights[{0}] = {1}", i, weights[i]);
        }
        int sum = weights[weights.Length - 1];
        int number_rand = rand(sum);
        Console.WriteLine("number_rand = {0}", number_rand);

        if (0 <= number_rand && number_rand < weights[0])
        {
            Console.WriteLine("{0} <= {1} < weights[0]={2}", 0, number_rand, weights[0]);
            return 0;
        }
        for (int i = 1; i < weights.Length; i++)
        {
            if (weights[i - 1] <= number_rand && number_rand < weights[i])
            {
                Console.WriteLine("weights[{0}]={1} <= {2} < weights[{3}]={4}", i - 1, weights[i - 1], number_rand, i, weights[i]);
                return i;
            }
        }
        return -1;
    }

    static int rand(int n)
    {
        Random rd = new Random();
        return rd.Next(1, n + 1);
    }
}

输出

weights[1] = 10
weights[2] = 13
weights[3] = 14
number_rand = 12
weights[1]=10 <= 12 < weights[2]=13
return reward is 2

补充

  • 在循环中累计权重,并检查随机数是否在权重区间内,这样的话一旦命中就能省略了之后的计算。

改进后的代码

using System;

namespace Test
{
    class Program
    {

        static void Main(string[] args)
        {
            int[] table = new int[] { 1, 2, 1, };
            Console.WriteLine("result = " + RandomByWeight(table));

            Console.Read();
        }

        public static int RandomByWeight(int[] weights)
        {
            int sum = 0;
            for (int i = 0; i < weights.Length; i++)
            {
                sum += weights[i];
            }
            int number_rand = rand(sum);
            Console.WriteLine("number_rand = " + number_rand);

            int sum_temp = 0;

            for (int i = 0; i < weights.Length; i++)
            {
                sum_temp += weights[i];
                if (number_rand <= sum_temp)
                {
                    return i;
                }
            }

            return -1;
        }

        static int rand(int n)
        {
            Random rd = new Random();
            // 注意,返回值是左闭右开,所以maxValue要加1
            return rd.Next(1, n + 1);
        }

    }
}

输出

number_rand = 4
result = 2

你可能感兴趣的:(笔试题)