Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...