2012-12-25 83 views
0

可能重複:
How to randomize a javascript array?JavaScript中的一組數字的隨機排列

我寫的代碼在JavaScript中,我需要35個的輸入值,指定每個他們在一個數組中的地方,然後洗牌,這樣他們將以不同的順序重新排列。作爲這樣:

var sort = new Array(35); 
sort[0] = document.getElementById("d1p1").value; 
sort[1] = document.getElementById("d1p2").value; 
// ... 
// ... (till 35) 
var rand1 = Math.floor(Math.random() * 35); 
var rand2 = Math.floor(Math.random() * 35); 
// ... 
// ... (till 35) 
var rsort = new Array(35); 
rsort[rand1] = document.getElementById("d1p1").value; 
rsort[rand2] = document.getElementById("d1p2").value; 

唯一的問題是,由於Math.floor(的Math.random()* 35)生成一些相同的號碼從1-35不止一次(好,我想這是點的隨機性),那麼兩個值有時被分配相同的輸入框,並且它們返回 undefined。有任何想法嗎?

回答

5

你應該以產生值在隨機排列均勻分佈做的是做這樣的:

  • 挑選從0隨機指數35,並與指數掉期的第一個值
  • 然後挑從1另一隨機索引至35和與該索引
  • 繼續像這樣對所有剩餘的索引交換的第二個值(2 - 35)

這裏的一個潛在執行:

// first make a copy of the original sort array 
var rsort = new Array(sort.length); 
for(var idx = 0; idx < sort.length; idx++) 
{ 
    rsort[idx] = sort[idx]; 
} 

// then proceed to shuffle the rsort array  
for(var idx = 0; idx < rsort.length; idx++) 
{ 
    var swpIdx = idx + Math.floor(Math.random() * (rsort.length - idx)); 
    // now swap elements at idx and swpIdx 
    var tmp = rsort[idx]; 
    rsort[idx] = rsort[swpIdx]; 
    rsort[swpIdx] = tmp; 
} 
// here rsort[] will have been randomly shuffled (permuted) 

我希望這有助於。

+0

進行復印是VAR rsort = sort.slice容易()。 – Stefan

+1

好點Stefan - 有不止一種方法去皮膚貓) –

-1

您可以使用此other answer改編的這個小函數。另外,我會使用一個類,以便抓住所有輸入。

function randomArray(min, max) { 
    return (new Array(max-min)) 
    .join(',').split(',') 
    .map(function(v,i){ return [Math.random(), min + i]; }) 
    .sort().map(function(v) { return v[1]; }); 
} 

var inputs = document.querySelectorAll('.myinput'); 

// Creates an array with all your input elements in random order 
var randomInputs = randomArray(0, inputs.length).map(function(n){ 
    return inputs[ n ]; 
}); 

演示:http://jsbin.com/uyaqed/1/edit(Ctrl + Enter以刷新)

+0

這是一種糟糕的隨機洗牌方式,它效率低下(洗牌比排序更容易)和不正確(比較函數應該與總排序一致要素)。 – 6502

+0

嗯......看不出爲什麼這是一種糟糕的方式和不正確的..它工作得很好,我以前在其他項目中使用它,並完成這項工作。 – elclanrs

+0

@ 6502:點擊此處查看演示http://jsbin.com/uyaqed/1/edit – elclanrs