0

I have different rectangle objects that each have an unique ID generated via a Guid.

Example ID: "fdd4551f-0087-48ee-b764-3713b5107ac9"

I want to convert that string into an integer from 0 to 256 so I can assign a random color to each object depending on their IDs.

Example of expected results:

For

"fdd4551f-0087-48ee-b764-3713b5107ac9" = 186

"48d32306-2861-4e78-b57e-9a02ce92f8ed"  = 35 

I don't really care what the numbers are except that I always get the same result with the same random string.

Luka Lovre
  • 13
  • 1
  • 2
  • 1
    Are you OK with getting the same number for two different strings? – Joe Sewell Oct 08 '19 at 18:09
  • Sure, I guess it's inevitable since the result pool has only 256 numbers. – Luka Lovre Oct 08 '19 at 18:10
  • 2
    I think your requirements need to be fleshed out more. This solution meets your current requirements, but I doubt this is what you had in mind: `int GetNumber(string intput) { return 6; /* chosen by fair die roll */ }` –  Oct 08 '19 at 18:11
  • I guess the problem would be solved if I could use a string for the Random seed, but it only has integer input – Luka Lovre Oct 08 '19 at 18:19
  • Now I see that I can get the integer from a string via `GetHashCode()` but I might not always return the same value. I might need to get the numbers for all the characters and add them up together, then just do a module by 256 – Luka Lovre Oct 08 '19 at 18:24
  • 1
    Use GetHashCode() and convert the result into 4 bytes and XOR them together. – Matthew Watson Oct 08 '19 at 18:27

1 Answers1

3

Given the relatively loose requirements, this can be a one-liner:

static int GetNumberForString(string guid, int limit)
{
    return Math.Abs(guid.GetHashCode()) % limit;
}
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • There isn't a guarantee that Guid.GetHashCode() will return the same value between different implementations of .NET. Not sure whether that is relevant to the OP. – Eric J. Oct 08 '19 at 18:44
  • See this if a stable hash code is important https://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-overriding-gethashcode/263416#263416 – Eric J. Oct 08 '19 at 18:46