![](/img/trans.png)
[英]Randomly pick array values, add them up, until you get a certain value in php
[英]Randomly sum values, add/subtract them up, until you have a value match php
我有一個值浮動數組:
$values =array(); // array(6) { [0]=> string(8) "90.00000" [1]=> string(9) "481.93000" [2]=> string(8) "38.11000" [3]=> string(8) "-4.40000" [4]=> string(9) "120.00000" [5]=> string(10) "-120.00000" }
$value_to_be_found = 123.710;
現在 e 需要一些東西來隨機總結它們,直到找到 $value_to_be_found。
在這種情況下,答案是:
90.00000
38.11000
-4.40000
可以為此進行大量優化,但我認為源數據可以比循環更優化,所以我將保留它。
假設您將此作為輸入數據,特別是存儲為字符串的類似浮點值的數組,以及存儲為浮點數的搜索值。
$numbers = ['90.00000', '481.93000', '38.11000', '-4.40000', '120.00000', '-120.00000'];
$sum = 123.710;
下面的代碼應該可以工作,我在里面
function _searchRecursive($numbers, $sum, &$result, $index = 0, $total = 0, $solution = '')
{
// The logic in the block following this one works on strings, this converts it back to an integer array
if ($total === $sum) {
$result = array_map('intval', explode(' ', trim($solution)));
return true;
}
// This logic is from: https://stackoverflow.com/a/2687982/231316
if ($index < count($numbers)) {
return _searchRecursive($numbers, $sum, $result, $index + 1, $total, $solution) or _searchRecursive($numbers, $sum, $result, $index + 1, $total + $numbers[$index], $solution . ' ' . $numbers[$index]);
}
return false;
}
function search(array $numbersAsStrings, $sum)
{
// This is a magic multiple, adjust for your data or else things won't work!
$multiplier = 100000;
// Clone the array so that we can return strings later
$numbersAsInts = $numbersAsStrings;
// Create an integer array by multiplying each number and casting to int
foreach ($numbersAsInts as &$number) {
$number = (int)($number * $multiplier);
}
// The previous loop is by reference so it is best to clean up
unset($number);
// Scale our search term, too
$sum = (int)($sum * $multiplier);
// The recursive search will place the value into this, if found
$result = null;
_searchRecursive($numbersAsInts, $sum, $result);
// Nothing was found
if (!is_array($result)) {
return null;
}
// Search the original string array and re-match with our int array
$finalRet = [];
foreach ($result as $int) {
foreach ($numbersAsStrings as $string) {
if ($int === (int)($string * $multiplier)) {
$finalRet[] = $string;
break;
}
}
}
return $finalRet;
}
$result = search($numbers, $sum);
在線版本: https://3v4l.org/Y9T8K
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.