0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

重みづけ抽選関数

Posted at

c#で書いた重みづけ抽選関数。タプルを利用しています。
シンプルなので使いやすいかと。

 RandomPickWithWeight.cs
    int RandomPickWithWeight(List < (int id, float weight) > lst) {
        var sum = 0f;
        foreach (var l in lst) {
            sum += l.weight;
        }
        var lot = Random.value * sum;
        sum = 0f;
        foreach (var l in lst) {
            sum += l.weight;
            if (sum >= lot) {
                return l.id;
            }
        }
        return lst[0].id;
    }

準備しておく重みづけ付き抽選対象の例。

RewardData.cs

        enum REWARD_TYPE {
            Rarecoin,
            Ticket,
            XP
        }

        List < (int id, float weight) > _rewardsWeight = new List < (int id, float weight) > {
            ((int)REWARD_TYPE.Rarecoin, 30f),
            ((int)REWARD_TYPE.Ticket, 10f),
            ((int)REWARD_TYPE.XP, 5f),
        };

上記例に書いたListを関数に食わせるとintを返すので(REWARD_TYPE)にcastすると扱いやすい答えが得られます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?