设定百分比,使它看起来是随机的 [英] setting Percentages and making it look random

查看:233
本文介绍了设定百分比,使它看起来是随机的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何设置的百分比也让他们看起来是随机的?

How do you set percentages well having them look random?

我了解如何使一个数组随机的。这是比较容易的部分。现在最困难的部分。
我想知道如何在一个阵列组的百分比,在每个项目以及有它看起来像阵列中的每个项目按随机顺序被显示。

I understand how to make an array random. that's the easy part. Now for the hard part. I would like to know how to set percentages on each item in an array well having it look like each item in that array is being shown in a random order.

您可以在一个阵列中的每个项目设定百分比?还是我们只随机一起工作呢?

can you set percentages for each item in an array? Or do we have only Random to work with?

推荐答案

要做到这一点,你必须在,以各种可能性相关联。它并不必须是一个百分比

To do this you have to associate a weight to each possibility. It doesn't have to be a percentage.

这将是一个通用的项目的一个例子具有重量

This would be an example of a generic item with a weight

public class WeightedItem<T>
{
    public T Item { get; set; }
    public int Weight { get; set; }

    public WeightedItem(T item, int weight=1)
    {
        Item = item;
        Weight = weight;
    }
}

要挑一个的随机的所有项目,你只要给权重较高的项目之一的更好的机会

To pick a random one of all your items you just give items with a higher weight a better chance

public static class WeightedRandomizer<T>
{
    private static System.Random _random;

    static WeightedRandomizer()
    {
        _random = new System.Random();    
    }

    public static T PickRandom(List<WeightedItem<T>> items)
    {
        int totalWeight = items.Sum(item => item.Weight);
        int randomValue = _random.Next(1, totalWeight);

        int currentWeight = 0;
        foreach (WeightedItem<T> item in items)
        {
            currentWeight += item.Weight;
            if (currentWeight >= randomValue)
                return item.Item;
        }

        return default(T);
    }
}

例如:

var candidates = new List<WeightedItem<string>>
{
    new WeightedItem<string>("Never", 0),
    new WeightedItem<string>("Rarely", 2),
    new WeightedItem<string>("Sometimes", 10),
    new WeightedItem<string>("Very often", 50),
};

for (int i = 0; i < 100; i++)
{
    Debug.WriteLine(WeightedRandomizer<string>.PickRandom(candidates));
}

这些项目的机会将是:

The chances for these items would be:

从不:0的62倍(0%)

"Never" : 0 of 62 times (0%)

很少:2的62倍(3.2%)

"Rarely" : 2 of 62 times (3.2%)

有时:62次10(16.1%)

"Sometimes" : 10 of 62 times (16.1%)

非常频繁:50 62次(80.6%)

"Very often": 50 of 62 times (80.6%)

不是字符串你当然可以使用任何其他类型的像的图像,数字或一类你自己的。

Instead of strings you can of course use any other type like an image, number or a class of your own.

这篇关于设定百分比,使它看起来是随机的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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