分配不同的结果最好的方法? [英] Best way to distribute different outcomes?

查看:91
本文介绍了分配不同的结果最好的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为的GetValue(),它应该返回值A的方法,B,C或D上的每个方法调用。

I have a method called "GetValue()" which is supposed to return the value "A", "B", "C" or "D" on each method call.

我希望此方法返回值A中的方法调用和在方​​法调用14%的值B,则值C31%30%..等等...

I want this method to return the value "A" in 30% of the method calls and the value "B" in 14% of the method calls, the value "C" 31%.. and so on...

至极的顺利分发theese价值的最好方式,我不希望该方法返回的值在连续becouse值AXXX次A是最远从它的请求的结果的百分比。

Wich is the best way to distribute theese values smoothly, I do not want the method to return the value "A" xxx times in a row becouse the value "A" are farest from it's requested outcome percentage.

请所有answeres是AP preciated。

Please, all answeres are appreciated.

推荐答案

您可以使用的 Random类来实现这一点:

You can use the Random class to achieve this:

private static Random Generator = new Random();

public string GetValue() 
{
  var next = Generator.Next(100);
  if (next < 30) return "A";
  if (next < 44) return "B";
  if (next < 75) return "C";
  return "D";
}

更新

有关更通用的随机权值店,下面可能是一个很好的起点:

For a more generic random weighted value store, the following may be a good starting point:

public class WeightedValueStore<T> : IDisposable
{
  private static readonly Random Generator = new Random();

  private readonly List<Tuple<int, T>> _values = new List<Tuple<int, T>>();
  private readonly ReaderWriterLockSlim _valueLock = new ReaderWriterLockSlim();

  public void AddValue(int weight, T value)
  {
    _valueLock.EnterWriteLock();
    try 
    {
      _values.Add(Tuple.Create(weight, value));
    }
    finally
    {
      _valueLock.ExitWriteLock();
    }
  }      

  public T GetValue() 
  {
    _valueLock.EnterReadLock();
    try
    {
      var totalWeight = _values.Sum(t => t.Item1);
      var next = Random.Next(totalWeight);
      foreach (var tuple in _values)
      {
        next -= tuple.Item1;
        if (next < 0) return tuple.Item2;
      }
      return default(T); // Or throw exception here - only reachable if _values has no elements.
    }
    finally
    {
      _valueLock.ExitReadLock();
    }
  }

  public void Dispose()
  {
    _valueLock.Dispose();
  }
}

那么这将是可用的,像这样:

Which would then be useable like so:

public string GetValue() 
{
  using (var valueStore = new WeightedValueStore<string>()) 
  {
    valueStore.AddValue(30, "A");
    valueStore.AddValue(14, "B");
    valueStore.AddValue(31, "C");
    valueStore.AddValue(25, "D");
    return valueStore.GetValue();
  }
}

这篇关于分配不同的结果最好的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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