2014-11-24 54 views
1

我有大約100個不同的隨機數的數組是這樣的:如何獲得帶有PHP條件的rendomise值?

$numbers=array(10,9,5,12, ..... .... ... ...); 

現在我想使隨機數的數組,從這個陣列,這樣addition of selected numbers will be my given number。例如:我可能會要求獲得一組數字,例如if i add all numbers it will be 100。 我試圖做這樣,

function rendom_num ($array,$addition) 
{ 
//here is the code 

} 
print_r (rendome_num ($numbers,100)); 

我不能夠到魔鬼的代碼,最近3天了!

+0

你可能是在洗牌之後應用了[Knapsack問題](http://en.wikipedia.org/wiki/Knapsack_problem)。 – 2014-11-24 05:00:21

回答

-1

東西只有一些隨機值像這樣應該可以工作。細分被評論,所以你知道這是做什麼。

function Randomizer($number = 100) 
     { 
      // This just generates a 100 number array from 1 to 100 
      for($i=1; $i <= 100; $i++) { 
        $array[] = $i; 
       } 
      // Shuffles the above array (you may already have this array made so you would need to input into this function) 
      shuffle($array); 
      // Assign 0 as base sum 
      $sum = 0; 
      // Go through the array and add up values 
      foreach($array as $value) { 
        // If the sum is not the input value and is also less, continue 
        if($sum !== $number && $sum < $number) { 
          // Check that the sum and value are not greater than the input 
          if(($sum + $value) <= $number) { 
            // If not, then add 
            $sum += $value; 
            $new[] = $value; 
           } 
         } 
        // Return the array when value hit 
        else 
         return $new; 
       } 
      // If the loop goes through to the end without a successful addition 
      // Try it all again until it does. 
      if($sum !== $number) 
       return Randomizer($number); 
     } 

    // Initialize function 
    $test = Randomizer(100); 

    echo '<pre>'; 
    // Total (for testing) 
    echo array_sum($test); 
    // Array of random values 
    print_r($test); 
    echo '</pre>'; 
+0

此代碼工作正常,但是當我刷新了幾次我得到了'警告:array_sum()期望參數1是數組,空行給出在E:\ software \ html \ index.php 29行上' – 2014-11-24 05:00:33

+0

這個算法有不停的潛力。 – 2014-11-24 05:06:14

+0

雖然我不得不改變這段代碼,但它幫了我很多:)謝謝 – 2014-11-24 05:09:08

1

請使用shuffle-

<?php 
$numbers = range(1, 20); 
shuffle($numbers); 
foreach ($numbers as $number) { 
    echo "$number "; 
} 
?> 

php.net

+0

這裏每次我會得到不同的號碼,但我需要採取這樣的方式,所有號碼的添加將是一個固定的數字。讓我們說100。 – 2014-11-24 04:33:01

0

可以使用shuffle作爲@chatfun說還是可以嘗試array_rand如果想從你的陣列

$value= array("Rabin","Reid","Cris","KVJ","John"); 
$rand_keys=array_rand($value,2); 
echo "First random element = ".$value[$rand_keys[0]]; 
echo "<br>Second random element = ".$value[$rand_keys[1]]; 
+0

我的問題不是關於洗牌,而是關於洗牌後的價值。 – 2014-11-24 04:36:59