pierre@1: . pierre@1: */ pierre@1: pierre@1: function ad_weight_probability_cache_filter($ads) { pierre@1: $display = array(); pierre@1: if (is_array($ads)) { pierre@1: $probability = array(); pierre@1: $cache = adserve_cache('get_cache', 'weight'); pierre@1: foreach ($ads as $aid) { pierre@1: $probability[] = isset($cache['probability'][$aid]) ? $cache['probability'][$aid] : 0; pierre@1: } pierre@1: $gcd = ad_weight_probability_gcd($probability); pierre@1: _debug_echo("ad_weight_probability cache_filter gcd($gcd)"); pierre@1: foreach ($ads as $aid) { pierre@1: $weight = (isset($cache['probability'][$aid]) && $gcd) ? $cache['probability'][$aid] / $gcd : 0; pierre@1: _debug_echo("ad_weight_probability cache_filter aid($aid) weight($weight)"); pierre@1: for ($i = 1; $i <= $weight; $i++) { pierre@1: $display[] = $aid; pierre@1: } pierre@1: } pierre@1: } pierre@1: return $display; pierre@1: } pierre@1: pierre@1: /** pierre@1: * Returns the greatest common divisor of an array of integers. pierre@1: */ pierre@1: function ad_weight_probability_gcd($integers) { pierre@1: $gcd = array_shift($integers); pierre@1: pierre@1: while (!empty($integers)) { pierre@1: $gcd = _ad_weight_probability_gcd($gcd, array_shift($integers)); pierre@1: } pierre@1: return $gcd; pierre@1: } pierre@1: pierre@1: /** pierre@1: * Helper function to calculate the greatest common divisor using the Euclidean pierre@1: * algorithm (http://en.wikipedia.org/wiki/Euclidean_algorithm). pierre@1: */ pierre@1: function _ad_weight_probability_gcd($a, $b) { pierre@1: if ($b == 0) { pierre@1: return $a; pierre@1: } pierre@1: else { pierre@1: return _ad_weight_probability_gcd($b, $a % $b); pierre@1: } pierre@1: }