Search code examples
c++randomc++14uniform-distribution

Algorithm to map string to a random number in range [0,100]


Requirement

Sorry it sounds like an homework assignment but I need this feature for a dll I'm implementing in our project.

  1. I have an array of strings.
  2. Each string is of length 16 of random chars [0-9a-z]
  3. I want to map each string to a random number in range [0,100]
  4. String 'X' will always be mapped to number 'Y'

Attempt

for (string strLine; std::getline(filein, strLine);)
{
    int iSum = 0;
    for (const auto& c : strLine)
        iSum += static_cast<int>(c);

    int iRand = iSum % 101;

    using namespace std;;

    fileout << strLine << "\t" << iSum << "\t" << iRand << endl;
}

Problem

I run this on a 1000 random strings. The results are not uniform. This is not a surprise since my mapping function is embarrassing.

I tried looking at Pseudo-random number generation and kinda got lost.


Solution

  • Why not just use the built-in std::hash

    #include <string>
    #include <functional>
    
    std::hash<std::string> hasher;
    iRand = hasher(strLine) % 101; // iRand will be in [0,100] range