Nel*_*ado 2 c# random unity-game-engine
我有一些时间思考以下内容,我想制作一个按钮来随机化一些技能的全部价值.问题是我有10分可以分配4种技能,想法是选择不超过10分的随机数.
我曾想过这个
public int startPts = 10, usedPts = 0;
public int skill1 = 0, skill2 = 0, skill3 = 0, skill4 = 0;
public void ButtonRandom(){
startPts = 10;
usedPts = 0;
skill1 = Random.Range( 1, 10 );
usedPts += skill1;
skill2 = Random.Range( 1, usedPts );
usedPts += skill2;
skill3 = Random.Range( 1, usedPts );
usedPts += skill3;
skill4 = startPts - usedPts;
usedPts += skill4;
startPts = startPts - usedPts;
}
Run Code Online (Sandbox Code Playgroud)
我也尝试了几种条件和重复方法,但我没有得到理想的结果.因为有时它超过了10个点,所以当我放置条件时,不使用或仅更改前2个值时离开点.
感谢你们.
如果您想要的是每个可能的分布同样可能,那么到目前为止所提供的解决方案都不起作用.到目前为止提出的解决方案选择3, 3, 2, 2
的频率要高得多7, 1, 1, 1
.你明白为什么吗?
如果您所需的分布在可能性上是均匀的,则此算法为您提供:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
// Partition n into m summands
static IEnumerable<IEnumerable<int>> Partitions(int n, int m)
{
// There is no partition of n into zero summands for any value of n other than zero.
// Otherwise, give the partitions that begin with 0, 1, 2, ... n.
if (m == 0)
{
if (n == 0)
yield return Enumerable.Empty<int>();
}
else
{
for (int nn = 0; nn <= n; ++nn)
foreach(var p in Partitions(n - nn, m - 1))
yield return (new[] { nn }).Concat(p);
}
}
public static void Main()
{
// Divide up six points into four buckets:
var partitions = Partitions(6, 4).ToArray();
// Now choose a random member of partitions, and
// add one to each element of that sequence. Now
// you have ten points total, and every possibility is
// equally likely.
// Let's visualize the partitions:
foreach(var p in partitions)
Console.WriteLine(string.Join(",", p));
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
295 次 |
最近记录: |