在C#中的随机加权 [英] Random weighting in C#
问题描述
我要创建C#中的游戏,游戏中的一个重要组成部分是随机性。它本质上是一个摔跤模拟器,其中'移动'被上取决于许多因素,如摔跤属性和当前动量一个表中选择
I'm creating a game in C#, and a crucial part of the game is randomness. It's essentially a wrestling simulator, where 'moves' are selected on a table depending on a number of factors, such as wrestlers attributes and current momentum.
接着出来的所有的移动的那场比赛这一标准,一个随机选择使用随机对象执行,跳过/在LINQ采取但这是真的不够。我想要做的就是被选中(我已经有这个就移动表中的列,为1和100之间的整数)的重量移动概率。我将如何实现这个加权到我的随意行选择?
Then out of all the moves that that match this criteria, a random one is selected to be executed using the Random object and Skip/Take in LINQ But this is really not enough. What I want to do is weight moves probability of being chosen (I already have a column on the moves table for this, for an integer between 1 and 100). How would I implement this weighting into my random row selection?
推荐答案
这是不是太困难。我没有代码,以便于工作,我假设你有对象移动
与属性重量
A阵列,所有的权重里面总结到100.0(其实并不重要)。
现在你排序权重decending阵列,通过挑选这一切都降低你的随机数0和99和迭代之间的随机数。只要它不积极了你停下来挑当前索引/移动
this is not too difficult. I have no code to work with so I assume you have objects Move
with an attribute Weight
inside a array and all weights sum up to 100.0 (don't really matter).
Now you sort the array by weights decending, pick a random number between 0 and 99 and iterate through all this decreasing your random number. As soon as it not positive anymore you stop and pick the current index/move
var value = rnd.NextDouble()*100.0;
foreach(var move in moves.OrderByDescending(m => m.Weight))
{
value -= move.Weight;
if (value <= 0) return move;
}
当然,你可以缓存排序,甚至选秀权成一个大阵列。使用一个随机指数这个(性能),但器的原理应该是清楚的,我希望
of course you can cache the ordering or even the picks into a big array and use a random-index into this (for performance) but the priciple should be clear I hope.
由于乔治建议 - 在这里是一个版本,你可以将假设在权重之和高达100:
As George suggested - here is a version where you can drop to assume that the weights sum up to 100:
double _weightSum;
...
// initialize the Sum somewhere
_weightSum = moves.SumBy(m => m.Weight);
Move GetRandomMove()
{
var value = rnd.NextDouble()*weightSum;
foreach(var move in moves.OrderByDescending(m => m.Weight))
{
value -= move.Weight;
if (value <= 0) return move;
}
}
这篇关于在C#中的随机加权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!