2014-02-14 78 views
0

我有一個5個數字的數組,並希望從我的數組中隨機選擇'任意3'數字
以產生下面的結果。我看了,找不到代碼
這將重現確切的結果。我在想一個用於廁所」與
功能將是最好的選擇,但我怎麼去了解它,任何幫助,(JavaScript中,
的Java,PHP)將被理解請從數組中選擇隨機值

var myArray = ["1","2","3","4","5"]; 
var result = myArray.slice(); 

for (i=0; i < result; i++) { 
    console.log(myArray[i]); 
} 

Results: 
1 2 3 
1 2 4 
1 2 5 
1 3 4 
1 3 5 
1 4 5 
2 3 4 
2 3 5 
2 4 5 
3 4 5 
+1

獲取的該boundarys一個隨機數數組大小並使用它來獲取元素。如何做到這一點真的取決於語言 – Mirco

回答

0

對於php您可以使用array_rand功能的幫助下,從HERE

你也可以使用:

shuffle($array)然後array_rand($array,3)

0

試試我的PHP示例:

<?php 
$a=array("1","2","3","4","5"); 

for($i=1;$i<10;$i++){ 
$random_keys=array_rand($a,3); 
echo $a[$random_keys[0]].$a[$random_keys[1]].$a[$random_keys[2]]; 
echo "<br>"; 
} 
?> 
0

你可以試試這個:

var myArray = ["1","2","3","4","5"]; 

for (i=0; i < 3; i++) { 
    console.log(myArray[Math.floor(Math.random() * (myArray.length - 1))]); 
} 
  • 的Math.random()返回0和1
  • myArray.length返回陣列長度
  • Math.floor(之間的浮動)的乘法
  • 回合的結果
0

下面是我會採取的步驟來獲得你想要的東西:

  1. 創建一個數字爲1到5的數組。
  2. 創建一個空結果數組,該數組將包含隨機選取的3個結果數組。
  3. 儘管結果數組的大小不是3,請執行以下操作:
  4. ...從數字數組中選取一個隨機數。
  5. ...只要該數字不在您的結果數組中,請將其添加到數組中。
  6. ...如果它已經在數組中,繼續選取並檢查,直到找到不在數組中的一個。

在PHP中,這裏是你如何能做到以上:

$numbers = array(1,2,3,4,5); 

// The for loop is just to show this algorithm run 10 times, 
// to demonstrate the "randomness" of the result. 

for ($i = 0; $i < 10; $i++) { 
    $random_three = array(); 
    while(sizeof($random_three) < 3) { 
    $random_pick = $numbers[array_rand($numbers)]; 
    while (in_array($random_pick, $random_three)) { 
     $random_pick = $numbers[array_rand($numbers)]; 
    } 
    array_push($random_three, $random_pick); 
    } 

    print implode($random_three, " "); 
    print "\n"; 
} 

輸出(您的結果不同):

2 5 1 
2 5 4 
3 1 5 
1 4 2 
3 2 5 
5 2 4 
4 2 3 
2 5 4 
1 4 5 
1 3 5