Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put number in range c#

Tags:

c#

hash

This is widely discussed maybe, but i can't find the proper answer yet. Here is my problem i want to put a number in current range, but the number is random. I don't use

Random rand = new Random(); 
rand.Next(0,100);

the number is from GetHashCode(), and i have to put it in range *[0, someArray.Length);

I tried :

int a = 12345;
int currentIndex = a.GetHashCode();
currentIndex % someArray.Length + someArrayLength

but it doesn't work. I will appreciate any help.

like image 386
Yoan Dinkov Avatar asked Jun 30 '26 16:06

Yoan Dinkov


1 Answers

I'd go for (hash & 0x7FFFFFFF) % modulus. The masking ensures that the input is positive, and then the remainder operator % maps it into the target range.

Alternatives include:

result = hash % modulus;
if(result < 0)
    result += modulus;

and

result = ((hash % modulus) + modulus) % modulus

What unfortunately doesn't work is

result = Math.Abs(hash) % modulus

because Math.Abs(int.MinValue) is int.MinValue and thus negative. To fix this approach one could cast to long:

result = (int)(Math.Abs((long)hash)) % modulus)

All of these methods introduce a minor bias for some input ranges and modulus values, since unless the number of input values is an integral multiple of the modulus they can't be mapped to each output value with the same probability. In some contexts this can be a problem, but it's fine for hashtables.

If you mainly care about performance then the masking solution is preferable since & is cheap compared to % or branching.

like image 166
CodesInChaos Avatar answered Jul 02 '26 06:07

CodesInChaos