/** * Calculate the product of values in an array * * @param array $array * @return int */ public function product($array) { if (!isset($array)) { return null; } return array_product((array) $array); }
function factorial($num) { if ($num == 0) { return 1; } return array_product(range(1, $num)); }
public function calculateRibbon($dimension) { $dimension = $this->dimensionsToArray($dimension); asort($dimension, SORT_NUMERIC); $smallest = array_values(array_slice($dimension, 0, 2)); return $smallest[0] * 2 + $smallest[1] * 2 + array_product($dimension); }
function process($input, $compartments = 3) { for ($i = 0, $minFg = 0, $minQe = 0, $perGroup = array_sum($input) / $compartments; $i < 100;) { for ($inp = $input, $group = array_fill(1, $compartments, []); $val = array_pop($inp);) { $try = []; do { $g = rand(1, $compartments); $try[$g] = 0; $cs = array_sum($group[$g]); if ($cs > $perGroup) { continue 3; } } while ($cs >= $perGroup - $val && count($try) < $compartments); $group[$g][] = $val; } foreach ($group as $grp) { if (array_sum($grp) != $perGroup) { continue 2; } } if ($minFg == 0 || count($group[1]) <= $minFg) { $i++; $minFg = count($group[1]); $qe = array_product($group[1]); if ($minQe == 0 || $qe < $minQe) { $minQe = $qe; } } } return $minQe; }
private function _runAll() { $config = $this->manager; $idle = (bool) array_product($config->getLocks()); if (!$idle) { $this->watchDog(); return true; } // not using array_map() because error wont be thrown for ($jid = 0; $jid < count($this->jobs); $jid++) { $job = $this->jobs[$jid]; $jname = $this->manager->getJobName($jid); if (!$job->coolingDown()) { $job->lock(); $time = time(); $job->run(); $time = time() - $time; $job->unlock(); $this->logInfo("<Job Runned> job-name: {$jname}, time-elapsed: {$time}"); } else { $this->logInfo("<Job Blocked> job-name: {$jname}"); } } return true; }
public function product() { if (!isset($this->computed['product'])) { $this->computed['product'] = array_product($this->data); } return $this->computed['product']; }
private static function operacion($tipo, $liga, $col, $cond = false) { if ($liga->existe($col)) { if ($cond && is_string($cond) && strpos($cond, '#[') !== false) { $cond = str_replace('#[', '@[', $cond); $num = 0; $con = 0; $pasa = 0; while ($liga->filas()) { if ($liga->cond(++$con, $cond) && ($dato = strval($liga->dato($con, $col)))) { if ($tipo == 'prod') { $num ? $num *= $dato : ($num = $dato * 1); } else { $num += $dato; } $pasa++; } } return $tipo == 'prom' ? $num / $pasa : $num; } $col = $liga->columna($col); if ($tipo == 'sum') { return array_sum($col); } elseif ($tipo == 'prod') { return array_product($col); } return array_sum($col) / $liga->numReg(); } return "No existe la columna '{$col}'"; }
/** * @param mixed $a * @param mixed $b * @return mixed * @throw Exception */ public function render($a = NULL, $b = NULL) { if ($a === NULL) { $a = $this->renderChildren(); } if ($a === NULL) { throw new Exception('Required argument "a" was not supplied', 1237823699); } if ($b === NULL) { throw new Exception('Required argument "b" was not supplied', 1237823699); } $aIsIterable = $this->assertIsArrayOrIterator($a); $bIsIterable = $this->assertIsArrayOrIterator($b); if ($aIsIterable === TRUE) { if ($b === NULL) { return array_product($a); } $aCanBeAccessed = $this->assertSupportsArrayAccess($a); $bCanBeAccessed = $this->assertSupportsArrayAccess($b); if ($aCanBeAccessed === FALSE || $bCanBeAccessed === FALSE) { throw new Exception('Math operation attempted on an inaccessible Iterator. Please implement ArrayAccess or convert the value to an array before calculation', 1351891091); } foreach ($a as $index => $value) { $a[$index] = $value * ($bIsIterable === TRUE ? $b[$index] : $b); } return $a; } elseif ($bIsIterable === TRUE) { // condition matched if $a is not iterable but $b is. throw new Exception('Math operation attempted using an iterator $b against a numeric value $a. Either both $a and $b, or only $a, must be array/Iterator', 1351890876); } return $a * $b; }
/** * Classifies a document string and returns the top N predicted classes and their scores. * * @param string $document The document to classify * @param int $top Number of top classes to return. * * @return array A descendingly sorted list of classes and their scores. Example: array("class" => "score", ...) */ public function classify($document, $top = 5) { $words = $this->normalize(explode(" ", $document)); $classes = $this->store->getAllClasses(); //prior probabilities $priors = array(); $totalDocuments = $this->store->getDocumentCount(); foreach ($classes as $class) { $priors[$class] = $this->store->getClassCount($class) / $totalDocuments; } //vocabulary $vocabulary = $this->store->countVocabulary(); //conditional probabilities $conditionals = array(); foreach ($classes as $class) { foreach ($words as $word) { $countWordInClass = $this->store->countWordInClass($word, $class); $wordsInClass = $this->store->countWordsInClass($class); $conditionals[$class][$word] = ($countWordInClass + 1) / ($wordsInClass + $vocabulary + 1); } } //probabilities $probabilities = array(); foreach ($classes as $class) { $probabilities[$class] = $priors[$class] * array_product($conditionals[$class]); } //sort arsort($probabilities); return array_slice($probabilities, 0, $top); }
/** * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return int|void */ protected function execute(InputInterface $input, OutputInterface $output) { $this->detectMagento($output); if ($this->initMagento()) { if (\Mage::helper('core')->isModuleEnabled('Nexcessnet_Turpentine')) { $admin = \Mage::getModel('turpentine/varnish_admin'); $cfgr = $admin->getConfigurator(); if (!$cfgr) { throw new \RuntimeException('Could not connect to Varnish admin port. Please check settings (port, secret key).'); } $result = $cfgr->save($cfgr->generate()); # (success, optional_error) if (!$result[0]) { throw new \RuntimeException('Could not save VCL to disk: ' . $result[1]); } $result = $admin->applyConfig(); if (!(bool) array_product($result)) { throw new \RuntimeException('Could not apply VCL to all running Varnish instances'); } else { $output->writeln('<info>The Varnish VCL has successfully been generated and loaded.</info>'); } } else { $output->writeln('<error>Turpentine is not enabled or installed.</error>'); } } }
/** * Get the total score using the passed amount of ingredients. * * @param array $ingredient_counts Array of ingredients and their amount of spoons. * @return integer The total cookie score. */ private function _get_total_score($ingredient_counts) { $total_score_raw = $this->_get_total_score_raw($ingredient_counts); // Ignore the calories for the score. unset($total_score_raw['calories']); return array_product($total_score_raw); }
function calcSmallest($packets, $weight) { $checkStr = implode(array_fill(0, count($packets), 1)); $checkDec = bindec($checkStr); for ($i = 0; $i <= $checkDec; $i++) { $binStr = decbin($i); if (isset($smallest) && substr_count($binStr, "1") > $smallest[0]) { continue; } $binStrArr = str_split(str_pad($binStr, count($packets), "0", STR_PAD_LEFT)); $new_vals = []; foreach ($binStrArr as $key => $value) { $new_vals[] = $value * $packets[$key]; } $new_vals = array_filter($new_vals); if (array_sum($new_vals) == $weight) { $newLen = count($new_vals); $newQuan = array_product($new_vals); if (isset($smallest)) { if ($newLen <= $smallest[0] && $newQuan < $smallest[1]) { $smallest = [$newLen, $newQuan]; } } else { $smallest = [$newLen, $newQuan]; } } } return $smallest[1]; }
/** * Get the product of all the gifts in a given area. * * @param string $area * * @return number */ public function getAreaQuantumEntanglement($area = "passenger") { if (array_key_exists($area, $this->sleighArea)) { return array_product($this->sleighArea[$area]); } return false; }
function valueOf(array $portions) { global $ingredients; if (count($portions) != count($ingredients)) { throw new Exception('count mismatch'); } if (array_sum($portions) !== 100) { throw new Exception('Not 100'); } $take = ['capacity', 'durability', 'flavor', 'texture']; $values = []; $calories = 0; foreach ($portions as $id => $portion) { foreach ($take as $ing) { $values[$ing] += $ingredients[$id][$ing] * $portion; } $calories += $ingredients[$id]['calories'] * $portion; } if (PART_B && $calories !== 500) { return 0; } //if any is negative the product is 0; foreach ($values as $val) { if ($val < 0) { return 0; } } return array_product($values); }
/** * Helper that returns array of accent less vars. * * @since 3.0.0 * * @param Presscore_Lib_LessVars_Manager $less_vars * @return array Returns array like array( 'first-color', 'seconf-color' ) */ function presscore_less_get_accent_colors(Presscore_Lib_LessVars_Manager $less_vars) { // less vars $_color_vars = array('accent-bg-color', 'accent-bg-color-2'); // options ids $_test_id = 'general-accent_color_mode'; $_color_id = 'general-accent_bg_color'; $_gradient_id = 'general-accent_bg_color_gradient'; // options defaults $_color_def = '#D73B37'; $_gradient_def = array('#ffffff', '#000000'); $accent_colors = $less_vars->get_var($_color_vars); if (!array_product($accent_colors)) { switch (of_get_option($_test_id)) { case 'gradient': $colors = of_get_option($_gradient_id, $_gradient_def); break; case 'color': default: $colors = array(of_get_option($_color_id, $_color_def), null); } $less_vars->add_hex_color($_color_vars, $colors); $accent_colors = $less_vars->get_var($_color_vars); } return $accent_colors; }
function findNumbers($numbers, $target, $set = [], &$minCount = PHP_INT_MAX, &$minProduct = PHP_INT_MAX) { $count = count($set); $result = false; if ($count < $minCount) { while ($value = array_pop($numbers)) { if ($value < $target) { $newSet = $set; $newSet[] = $value; // reduce $target by $value and do another run $newResult = findNumbers($numbers, $target - $value, $newSet, $minCount, $minProduct); if ($newResult) { $result = $newResult; } } elseif ($value == $target) { $set[] = $value; $count = $count + 1; $product = array_product($set); // set current set as best when it has fewer numbers or has a lower product if ($count < $minCount || $count == $minCount && $product < $minProduct) { $minCount = $count; $minProduct = $product; return $set; } } } } return $result; }
/** * (non-PHPdoc) * @see SMWResultPrinter::getResultText() */ protected function getResultText(SMWQueryResult $res, $outputmode) { $numbers = $this->getNumbers($res); if (count($numbers) == 0) { return $this->params['default']; } switch ($this->mFormat) { case 'max': return max($numbers); break; case 'min': return min($numbers); break; case 'sum': return array_sum($numbers); break; case 'product': return array_product($numbers); break; case 'average': return array_sum($numbers) / count($numbers); break; case 'median': sort($numbers, SORT_NUMERIC); $position = (count($numbers) + 1) / 2 - 1; return ($numbers[ceil($position)] + $numbers[floor($position)]) / 2; break; } }
public function testEqualToNative() { $this->forAll(Generator\seq(Generator\int()))->__invoke(function ($arr) { $e = array_product($arr); $this->assertEquals($e, lazy_product($arr)->resolve()); $this->assertEquals($e, lazy_product(new \ArrayObject($arr))->resolve()); }); }
public function totalScoreForRecipe(array $properties = ["capacity", "durability", "flavour", "texture"]) { $scores = []; foreach ($properties as $property) { $scores[] = $this->totalScoreForProperty($property); } return array_product($scores); }
public function __invoke() { \ini_set("memory_limit", "4G"); $input = $this->loadInput("Day24/Puzzle1"); $loader = new SledLoader(explode(PHP_EOL, $input)); $optimal = $loader->optimalFrontLoading(); $this->write("Optimal: " . implode(',', $optimal)); $this->write("QE: " . array_product($optimal)); }
function foo() { $a = array(); $a[] = '1.1'; $a[] = '2.2'; $a[] = '3.3'; var_dump(array_sum($a)); var_dump(array_product($a)); }
public function optimalFrontLoading($sections = 3) { $waysofLoadingFront = $this->loadFront($sections); return array_reduce($waysofLoadingFront, function ($carry, $item) { if (!$carry || array_product($item) < $carry) { return $item; } return $carry; }); }
function geometricMean(array $array) { foreach ($array as $arg) { if (!is_numeric($arg)) { trigger_error("not a numeric value", E_USER_NOTICE); return false; } } return pow(array_product($array), 1 / count($array)); }
/** * @param string $category image category * @param string $name image name * @return bool return true if all file deleted */ public function delete($category, $name) { $directory = \Yii::getAlias($this->owner->imagesPath); $imagePath = implode(DIRECTORY_SEPARATOR, [$directory, $category]); $images = glob(implode(DIRECTORY_SEPARATOR, [$imagePath, "{$name}-*.*"])); // if not found image with name $name if (empty($images)) { return false; } return (bool) array_product(array_map('unlink', $images)); }
/** * @return mixed * @throw Exception */ public function render() { $a = $this->getInlineArgument(); $b = $this->arguments['b']; $aIsIterable = $this->assertIsArrayOrIterator($a); if (TRUE === $aIsIterable && NULL === $b) { $a = $this->convertTraversableToArray($a); return array_product($a); } return $this->calculate($a, $b); }
/** * @return mixed * @throw Exception */ public function render() { $a = $this->getInlineArgument(); $b = $this->arguments['b']; $aIsIterable = $this->assertIsArrayOrIterator($a); if (true === $aIsIterable && null === $b) { $a = $this->arrayFromArrayOrTraversableOrCSV($a); return array_product($a); } return $this->calculate($a, $b); }
function politeness($n) { $factors = $this->primeFactors($n); foreach ($factors as $b => &$e) { if ($b > 2) { $e++; } else { unset($factors[$b]); } } return array_product($factors) - 1; }
public function getRibbonRequired() { $ribbonRequired = 0; foreach ($this->boxes as $boxDimensions) { $dimensionsArray = explode('x', $boxDimensions); sort($dimensionsArray); $ribbonLength = 2 * $dimensionsArray[0] + 2 * $dimensionsArray[1]; $bowRibbonLength = array_product($dimensionsArray); $ribbonRequired += $ribbonLength + $bowRibbonLength; } return $ribbonRequired; }
public function testValidatorBetween() { $validator = new Validator(); $this->assertTrue((bool) array_product($validator->validate(10))); $validator->add(new Min(1)); $this->assertTrue((bool) array_product($validator->validate(3))); $this->assertTrue((bool) array_product($validator->validate(11))); $this->assertFalse((bool) array_product($validator->validate(0))); $validator->add(new Max(10)); $this->assertTrue((bool) array_product($validator->validate(3))); $this->assertFalse((bool) array_product($validator->validate(11))); }
function scoreMix($mix, $properties) { unset($properties['calories']); $scores = array_map(function ($ingredients) use($mix) { $i = 0; $score = 0; foreach ($ingredients as $name => $value) { $score += $value * $mix[$i]; $i++; } return max(0, $score); }, $properties); return array_product($scores); }