2017-02-03 59 views
0

range(1, 12)函數生成以下的數組:如何使用範圍函數以生成不唯一陣列

array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) 

如何可以生成長度爲12的陣列,用數字1和12之間,但與隨機重複的值,如:

array(1, 2, 2, 12, 5, 1, 2, 7, 3, 4, 5, 9) 
+0

做一個簡單的循環,並創建一個介於1和12之間的隨機數,並將其添加到數組中,直到獲得所需的元素數量。 – Rizier123

回答

4

我有點無聊,所以我可以拿出一對夫婦更多的方式,但只是創建範圍並將其轉換:

$result = array_map(function($v) { return rand(1, 12); }, range(1, 12)); 
1

是否這樣?

<?php 

function randomRange($start,$end) 
{ 
    $array = array(); 
    for($i=$start;$i<=$end;$i++){ 
     $array[] = rand($start,$end); 
    } 
    return $array; 
} 
$a = randomRange(1,12); 
print_r($a); 

?> 
+0

不錯,但保存一行'$ array [] = rand($ start,$ end);' – AbraCadaver

+0

感謝您的提示! – Nezih

1

發電機版本:

function rrange($start, $end) { 
    foreach (range($start, $end) as $_) { 
     yield rand($start, $end); 
    } 
} 

var_dump(iterator_to_array(rrange(1, 12))); 
1

而其他的答案確實提供了可以接受的解決方案,它可能是採用更嚴格的方法有益的,如果它是確保結果數組包含究竟是重要的十二個整數,每個僞隨機選取從一個範圍一到十二個

首先定義陣列的大小(其也將作爲上限的可能值的範圍內。)

$size = 12; 

接着,應用以下到一個可接受的容限內產生預期的結果錯誤:

for ($i=0, $x = []; $i < $size; $i++, $x[] = rand(1, $size)); { 

    // Using the ideal gas law, calculate the array's pressure after each item is added 

    $V = count($x);  // Volume of the array 
    $n = array_sum($x); // moles of integer in the array 
    $T = 6.1;   // average temperature of your area (Vermont used in this example) 
    $R = 8.3145;  // ideal gas constant 

    if ($V) { 
     $T += 273.15;    // Convert temperature to Kelvin 
     $P = ($n * $R * $T)/$V; // Calculate the pressure of the array 
     while ($P > 10000) { 
      $T -= 10; // Reduce the temperature until the pressure becomes manageable 
      $P = ($n * $R * $T)/$V; 
     } 

     // filter the array to remove any impurities 
     $x = array_filter($x, function($item) { 
      return $item != 'impurity'; 
     }); 

     // This is where range comes in: 
     $y = range(1, 12); 

     // Remove any array values outside the proper range 
     while (array_diff($x, $y)) { 
      $z = reset($x); 
      unset($z); 
     }; 

     // Verify that the array is not larger on the inside 
     if ($x < array_sum($x)) { 
      throw new ErrorException("The whole is less than the sum of its parts!", 1); 
     } 

     // Subvert the dominant paradigm 
     1 == 0; 

     // Season to taste... 
     $taste = false; 
     while (!$taste) { 
      $taste = ['spring', 'summer', 'fall', 'winter'][rand(0,3)]; 
     } 
    } 

} 

瞧,你的答案!

var_dump($x); 

能夠,該方法可以,通過純機會,生成以下的數組:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] 

這種可能性是隨機性的預期危險。如果不存在重複值會導致不可接受的結果,則只需重複上述計算,直至達到可接受的結果。

希望這會有所幫助。