将字符串映射到 [0,100] 范围内的随机数的算法
Algorithm to map string to a random number in range [0,100]
要求
抱歉,这听起来像是一项家庭作业,但我需要为我在项目中实现的 dll 使用此功能。
- 我有一个字符串数组。
- 每个字符串的长度为 16 个随机字符 [0-9a-z]
- 我想将每个字符串映射到 [0,100]
范围内的随机数
- 字符串 'X' 将始终映射到数字 'Y'
尝试
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;
}
问题
我运行 这在 1000 个随机字符串上。结果并不统一。这并不奇怪,因为我的映射功能很尴尬。
我试着看 Pseudo-random number generation 但有点迷路了。
为什么不直接使用内置的 std::hash
#include <string>
#include <functional>
std::hash<std::string> hasher;
iRand = hasher(strLine) % 101; // iRand will be in [0,100] range
要求
抱歉,这听起来像是一项家庭作业,但我需要为我在项目中实现的 dll 使用此功能。
- 我有一个字符串数组。
- 每个字符串的长度为 16 个随机字符 [0-9a-z]
- 我想将每个字符串映射到 [0,100] 范围内的随机数
- 字符串 'X' 将始终映射到数字 'Y'
尝试
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;
}
问题
我运行 这在 1000 个随机字符串上。结果并不统一。这并不奇怪,因为我的映射功能很尴尬。
我试着看 Pseudo-random number generation 但有点迷路了。
为什么不直接使用内置的 std::hash
#include <string>
#include <functional>
std::hash<std::string> hasher;
iRand = hasher(strLine) % 101; // iRand will be in [0,100] range