A concrete example.
If i have a range of 1-300, how can a generate 5 unique numbers within that range using GUID "EDAAE218-FBF0-4B66-AEAF-FB036FBF69F4"
. Applying the same algorithm to the GUID should result in the same 5 numbers being chosen every time.
The input doesn't have to be a GUID, it's just acting as some sort of key.
Some context for the problem i am trying to solve. I have a hard coded List of values that contains roughly 300 or so elements. I am trying to find a way to select 20 elements from this list that always produces the same elements.
My idea was to generate a GUID which could be handed out to multiple users. When those users input the GUID into the app, the same 20 elements would be returned for everyone.
A guid is effectively a 128-bit number. So you can easily do this provided that the number of bits required to represent your numbers are fewer than the number of bits in the guid (128). You don't need to hash the guid or anything like that.
EDIT:
Now that I know what you need (i.e. a unique seed to be derived from a guid, you could do it this way) - but you could equally hand out a 32-bit number and avoid the guid-to-int conversion.
EDIT2: Using GetHashCode as per suggestion from comments above.
EDIT 3: Producing unique numbers.
static void Main(string[] args)
{
var guid = new Guid("bdc39e63-5947-4704-9e12-ec66c8773742");
Console.WriteLine(guid);
var numbers = FindNumbersFromGuid(guid, 16, 8);
Console.WriteLine("Numbers: ");
foreach (var elem in numbers)
{
Console.WriteLine(elem);
}
Console.ReadKey();
}
private static int[] FindNumbersFromGuid(Guid input,
int maxNumber, int numberCount)
{
if (numberCount > maxNumber / 2) throw new ArgumentException("Choosing too many numbers.");
var seed = input.GetHashCode();
var random = new Random(seed);
var chosenSoFar = new HashSet<int>();
return Enumerable.Range(0, numberCount)
.Select(e =>
{
var ret = random.Next(0, maxNumber);
while (chosenSoFar.Contains(ret))
{
ret = random.Next(0, maxNumber);
}
chosenSoFar.Add(ret);
return ret;
}).ToArray();
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments