【问题标题】:Advertisement System Tips广告系统提示
【发布时间】:2015-06-30 22:02:53
【问题描述】:

我正在创建一个广告系统,它会更频繁地显示出价最高者的广告。

这是我正在使用的表结构的示例,但经过简化...

+----+----------+------------------------+----------------------+-----+
| id | name     | image                  | destination          | bid |
+----+----------+------------------------+----------------------+-----+
| 1  | abc, co  | htt.../blah            | htt...djkd.com/      | 3   |
+----+----------+------------------------+----------------------+-----+
| 2  | facebook | htt.../blah            | htt...djkd.com/      | 200 |
+----+----------+------------------------+----------------------+-----+
| 3  | google   | htt.../blah            | htt...djkd.com/      | 78  |
+----+----------+------------------------+----------------------+-----+

现在,我正在从数据库中选择值,然后将它们插入到一个数组中,然后随机选择一个,类似于以下内容:

$ads_array = [];
$ads = Ad::where("active", "=", 1)->orderBy("price", "DESC");

if ($ads->count() > 0) {
    $current = 0;
    foreach ($ads->get() as $ad) {
        for ($i = 0; $i <= ($ad->price == 0 ? 1 : $ad->price); $i++) {
            $ads_array[$current] = $ad->id;
            $current++;
        }
    }

    $random = rand(0,$current-1);
    $ad = Ad::where("id", "=", $ads_array[$random])->first();

    ...
}

所以,本质上这是在将广告的 ID 插入数组1*$bid 次。遗憾的是(出于显而易见的原因),这是非常低效的,但这是我能想到的最佳方式。

有没有更好的方法从我的数据库中挑选出随机广告?同时仍然让出价更高的人有更高的展示机会?

【问题讨论】:

标签: php sql laravel probability ads


【解决方案1】:

看起来这可能会奏效(但所有功劳归于guy in the comments)

SELECT ads.*
FROM ads
ORDER BY -log(1.0 - rand()) / ads.bid
LIMIT 1

一个测试这个的脚本:

<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;', 'test', 'test');


$times = array();

// repeat a lot to have real values
for ($i = 0; $i < 10000; $i++) {
    $stmt = $pdo->query('SELECT ads.* FROM ads ORDER BY -log(1.0 - rand()) / bid LIMIT 1');
    $bid = $stmt->fetch()['bid'];
    if (isset($times[$bid])) {
        $times[$bid] += 1;
    } else {
        $times[$bid] = 1;
    }
}

// echoes the number of times one bid is represented
var_dump($times);

我从那个测试中得出的数字非常好:

// key is the bid, value is the number of times this bid is represented
array (size=3)
  200 => int 7106
  78 => int 2772
  3 => int 122

数学解释的进一步参考

许多重要的单变量分布都可以使用简单的封闭形式表达式通过反演进行采样。此处列出了一些最有用的。

示例 4.1(指数分布)。标准指数分布在 x > 0 上具有密度 f(x) = e−x。如果 X 具有此分布,则 E(X) = 1,我们写为 X∼Exp(1)。累积分布函数为 F(x) = P(X ? x) = 1 − e−x,其中 F−1(u) = −log(1 − u)。因此,对于 U ∼ U(0, 1) 取 X = − log(1 − U ),生成标准指数随机变量。互补反演使用 X = − log(U )。

率 λ > 0(且均值 θ = 1/λ)的指数分布在 0 ? x

来自http://statweb.stanford.edu/~owen/mc/Ch-nonunifrng.pdf

【讨论】:

  • 当你有这样的号码时,这就是分配的方式。我在那里添加了进一步的参考资料,但不要让我进一步解释,因为这远远超出了我的数学专业知识:)
  • 很遗憾,没有按预期工作。最低出价似乎更多。
  • 请注意,我不是数学家;所以这些疯狂的事情对我来说几乎没有任何意义,哈哈。我想我正在寻找可能在做这种类型的系统方面有一些经验并且可以解释他们使用的一些技巧的人的答案。
  • 可以做到这一点,数字证明在 2 分钟内完成编辑
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-19
  • 2011-09-30
  • 1970-01-01
相关资源
最近更新 更多