Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

c# - Probability Random Number Generator

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...