我正在制作一个购物网站,为每个人创建一个独特的折扣代码 我希望为此代码生成1%的折扣,例如:
x3M2qE => 10%
gh2WW4 => 20%
......
这些代码应该以这样的方式创建:生成90%的概率远小于10%的生成。
确定最佳和最佳算法并帮助我正确完成,
感谢。
答案 0 :(得分:2)
基本上,您想要的是加权随机值。所以10%的折扣往往超过90%。这是我在另一个项目中使用的(在Javascript中,但是将逻辑转换为PHP)。
对于每个折扣值,指定您想要查看的频率:
frequencies = [50, 20, 15, 10, 5, 5, 5, 5]
5% 10% 20% 30% 40% 70% 80% 90% <-- reference values for %
因此,115次中有50次,用户将获得10%的折扣。 我这样做是为了告诉你,你的频率不需要总共100。无论如何这都有效。 要调整频率,请更改该阵列中的值。其余代码不会改变。
然后使用此算法根据权重获取%的随机值。 (再次这是Javascript,翻译成PHP)
var frequenciesborders = [];
var maxfrequenciesindex = frequencies.length -1;
var total = 0;
// Get the total and the border values. This is calculated so if the frequencies are
// changed, the code will still work.
for (i = 0; i <= maxfrequenciesindex; i++)
{
total = total + frequencies[i];
if (i == 0)
{
frequenciesborders[i] = frequencies[i];
}
else
{
frequenciesborders[i] = frequenciesborders[i-1] + frequencies[i];
}
}
var randomnumber = Math.floor(Math.random() * total) + 1;
if ( (randomnumber >= 1) && (randomnumber <= frequenciesborders[0]) )
{
code = "5%";
}
if ( (randomnumber >= frequenciesborders[0] + 1) && (randomnumber <= frequenciesborders[1]) )
{
code = "10%";
}
if ( (randomnumber >= frequenciesborders[1] + 1) && (randomnumber <= frequenciesborders[2]) )
{
code = "20%";
}
if ( (randomnumber >= frequenciesborders[2] + 1) && (randomnumber <= frequenciesborders[3]) )
{
code = "30%";
}
if ( (randomnumber >= frequenciesborders[3] + 1) && (randomnumber <= frequenciesborders[4]) )
{
code = "40%";
}
if ( (randomnumber >= frequenciesborders[4] + 1) && (randomnumber <= frequenciesborders[5]) )
{
code = "70%";
}
if ( (randomnumber >= frequenciesborders[5] + 1) && (randomnumber <= frequenciesborders[6]) )
{
code = "80%";
}
if ( (randomnumber >= frequenciesborders[6] + 1) && (randomnumber <= frequenciesborders[7]) )
{
code = "90%";
}
好的,让我们解释一下:
下面:
frequenciesborders[0] = 50;
frequenciesborders[1] = 70;
frequenciesborders[2] = 85;
frequenciesborders[3] = 95;
frequenciesborders[4] = 100;
frequenciesborders[5] = 105;
frequenciesborders[6] = 110;
frequenciesborders[7] = 115;
通过调整频率值,可以改变范围的大小&#34;。范围越大,随机数在该范围内的变化就越大。
多次循环运行此操作以确保它为您提供可接受的结果。我对您的财务成功与折扣不负责任: - )。
A&#34; visual&#34;显示此算法的方法是:
0 50 70 85 95 100 105 110 115
-------------------------------------------------------------------------------------------------------------------
< 5% >< 10% >< 20% >< 30% ><40%><70%><80%><90%>
随机数落在0到115之间的范围内。范围越大,您在该折扣百分比内的可能性就越大。
答案 1 :(得分:1)
最佳代码:
$chances = [
'50%' => 60,
'10%' => 30,
'5%' => 5,
'4%' => 2,
'3%' => 1,
'2%' => 1,
'1%' => 1,
];
$max_chance = 0;
foreach($chances as $key => $val) {
$max_chance += $val;
}
$rand = mt_rand(1, $max_chance);
$cur = 0;
foreach($chances as $key => $val) {
$cur += $val;
if($rand <= $cur)
echo $key;
}