gpt4 book ai didi

algorithm - 如何在 C++ 中生成具有固定总和的随机值

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:29:17 26 4
gpt4 key购买 nike

我想连续生成 3 个 0 到 9 范围内的随机数,它们的总和应为给定的固定数。例如,对于给定的固定总和 15,一种可能的解决方案是 (3, 8, 4)。我怎样才能做到这一点 ?谢谢。

最佳答案

我们可以:

  1. 首先生成01之间的随机 float a,b,c
  2. 获取a,b,c
  3. a,b,c 除以 sum
  4. a,b,c乘以给定的整数和,然后将a,b,c四舍五入到最接近的整数
  5. 看看 sum(a, b, c) == given integer ?得到结果:再试一次

检查这个演示:

使用 boost 随机生成器:

#include <iostream>
#include <time.h>
#include <iomanip>
#include <boost/random.hpp>

int main()
{
static time_t seed = time(0);
boost::random::mt19937 RandomNumGen(seed++);
boost::random::uniform_real_distribution<> Range(0, 1);

int Desired_Integer = 15;
int Rand_Max = 9;
int Max_Itr = 100000000;
int Count = 0;
int SumABC[3][10] = { 0 };
float bias = 0.5;

float a, b, c;
for (int Loop = 1; Loop <= Max_Itr; ++Loop)
{
a = Range(RandomNumGen);
b = Range(RandomNumGen);
c = Range(RandomNumGen);

float Sum = a + b + c;
a = a / Sum;
b = b / Sum;
c = c / Sum;

//Round to the nearest integer;
int aI = static_cast<int>(a * Desired_Integer + bias), bI = static_cast<int>(b * Desired_Integer + bias), cI = static_cast<int>(c * Desired_Integer + bias);
if (aI <= Rand_Max && bI <= Rand_Max && cI <= Rand_Max && aI + bI + cI == Desired_Integer)
{
SumABC[0][aI]++;
SumABC[1][bI]++;
SumABC[2][cI]++;

Count++;
}
}

int PaddingWidth = 10;
std::cout << "\n" << Count << " in " << Max_Itr << " loops get desired outcome. \nDistribution of a,b,c: \n";
std::cout << "Number" << std::setw(PaddingWidth) << "a" << std::setw(PaddingWidth) << "b" << std::setw(PaddingWidth) << "c" << std::endl;
for (int i = 0; i < 10; i++)
{
std::cout
<< i << std::setw(PaddingWidth + 8)
<< std::setprecision(4) << 100.0 * SumABC[0][i] / (float)Count << std::setw(PaddingWidth)
<< std::setprecision(4) << 100.0 * SumABC[1][i] / (float)Count << std::setw(PaddingWidth)
<< std::setprecision(4) << 100.0 * SumABC[2][i] / (float)Count << std::endl;
}

std::cout << "\n\n";

system("pause");
return 0;
}

测试效率:

Test distribution of numbers in 100000000 loops

关于algorithm - 如何在 C++ 中生成具有固定总和的随机值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40837939/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com