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

210 Views Asked by At

I have a C# script that extracts 5 digits from a random BigInteger that is 20 digits long. This is then cast to an int value between 0 and 99,999. I would like to use this number to determine the name of a character using a set of 113 strings. 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. 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?

1

There are 1 best solutions below

0
Eric J. On

You can divide it into N ranges where N > 113 and assign multiple values to strings you want to be more common. 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...)