简体   繁体   English

如何将非统一的 int 范围映射到 C# 中的某些字符串值?

[英]How do I map non-uniform int ranges to certain string values in C#?

I have a C# script that extracts 5 digits from a random BigInteger that is 20 digits long.我有一个 C# 脚本,它从一个 20 位长的随机 BigInteger 中提取 5 位数字。 This is then cast to an int value between 0 and 99,999.然后将其转换为 0 到 99,999 之间的 int 值。 I would like to use this number to determine the name of a character using a set of 113 strings.我想使用这个数字来确定使用一组 113 个字符串的字符的名称。 The reason I'm having trouble figuring this out is because I don't want the each of the 113 strings to have an equal chance of being chosen, so I can't just use the modulus operator to get an index for the set of strings.我无法弄清楚这一点的原因是因为我不希望 113 个字符串中的每一个都有相等的被选中机会,所以我不能只使用模数运算符来获取一组的索引字符串。 I want the mapping to be non-uniform so that certain names are rarer than others.我希望映射是非统一的,以便某些名称比其他名称更罕见。 For example, something like:例如,类似于:

        if(val <= 1000)
        {
            name = names[0];
        }
        if(val > 1000 && val <= 1250)
        {
            name = names[1];
        }
        if(val > 1250 && val <= 1750)
        {
            name = names[2];
        }

Is there any way to map non-uniform ranges like this in an efficient way without explicitly typing 113 different ranges out?有没有办法以有效的方式映射这样的非均匀范围,而无需明确输入 113 个不同的范围?

You can divide it into N ranges where N > 113 and assign multiple values to strings you want to be more common.您可以将其划分为 N > 113 的 N 个范围,并为您希望更常见的字符串分配多个值。 A simple approach is to have an array of strings and create multiple entries for strings you want to be most common, then use the modulus of the array length as the index into the array.一个简单的方法是拥有一个字符串数组并为您想要最常见的字符串创建多个条目,然后使用数组长度的模数作为数组的索引。

var strings = new string[] 
{
    "Foo",
    "Foo",
    "Bar",
    "Baz"
};

int someNumber = 77777;
var index = someNumber % strings.Length;
var myString = strings[index];

Of course, this approach doesn't give fine-grained control over the chance of any given string (unless you create an array with 100,000 entries...)当然,这种方法不会对任何给定字符串的可能性进行细粒度控制(除非您创建一个包含 100,000 个条目的数组...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM