概率随机数发生器 [英] Probability Random Number Generator

查看:106
本文介绍了概率随机数发生器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我正在写一个简单的运气的游戏 - 每个玩家presses输入和游戏赋予了他1-6之间的随机数。就像一个立方体。在比赛结束后,有最多的玩家获胜。

现在,让我们说我是个骗子。我想要写的游戏,所以播放器#1(这将是我)具有90%的概率得到6和2%以获得每个其余的数字(1,2,3,4,5)。

我如何能产生一些随机的,并设置概率各是多少?


解决方案

 静态随机随机=新的随机();静态INT CheatToWin()
{
    如果(random.NextDouble()&所述; 0.9)
        返回6;    返回random.Next(1,6);
}

另一种方式定制欺骗:

 静态INT IfYouAintCheatinYouAintTryin()
{
    列表与LT元组LT;双,INT>> iAlwaysWin =新的List&LT元组LT;双,INT>>();
    iAlwaysWin.Add(新行<双,INT>(0.02,1));
    iAlwaysWin.Add(新行<双,INT>(0.04,2));
    iAlwaysWin.Add(新行<双,INT>(0.06,3));
    iAlwaysWin.Add(新行<双,INT>(0.08,4));
    iAlwaysWin.Add(新行<双,INT>(0.10,5));
    iAlwaysWin.Add(新行<双,INT>(1.00,6));    双realRoll = random.NextDouble(); //相同的随机对象之前
    的foreach(在iAlwaysWin VAR骗子)
    {
        如果(cheater.Item1> realRoll)
            返回cheater.Item2;
    }    返回6;
}

Let's say I'm writing a simple luck game - each player presses Enter and the game assigns him a random number between 1-6. Just like a cube. At the end of the game, the player with the highest number wins.

Now, let's say I'm a cheater. I want to write the game so player #1 (which will be me) has a probability of 90% to get six, and 2% to get each of the rest numbers (1, 2, 3, 4, 5).

How can I generate a number random, and set the probability for each number?

解决方案

static Random random = new Random();

static int CheatToWin()
{
    if (random.NextDouble() < 0.9)
        return 6;

    return random.Next(1, 6);
}

Another customizable way to cheat:

static int IfYouAintCheatinYouAintTryin()
{
    List<Tuple<double, int>> iAlwaysWin = new List<Tuple<double, int>>();
    iAlwaysWin.Add(new Tuple<double, int>(0.02, 1));
    iAlwaysWin.Add(new Tuple<double, int>(0.04, 2));
    iAlwaysWin.Add(new Tuple<double, int>(0.06, 3));
    iAlwaysWin.Add(new Tuple<double, int>(0.08, 4));
    iAlwaysWin.Add(new Tuple<double, int>(0.10, 5));
    iAlwaysWin.Add(new Tuple<double, int>(1.00, 6));

    double realRoll = random.NextDouble(); // same random object as before
    foreach (var cheater in iAlwaysWin)
    {
        if (cheater.Item1 > realRoll)
            return cheater.Item2;
    }

    return 6;
}

这篇关于概率随机数发生器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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