2016-03-24 28 views
0

如果我有一個數組給我9個隨機數,從9個數字的列表中,我如何確保它只能複製3個相同的數字?例如,如果我的隨機數組是[4,3,4,4,7,8,8,8,9],則爲 。 我需要在那裏只有一個數組在任何一個數組中的三個不像上面看到的兩個。3個數字相同從1-9之間的隨機數列表

+4

可以共享代碼產生這些隨機數字? – gurvinder372

回答

0

你需要有什麼是你正在使用存儲被添加到陣列中的隨機數來代替randomNum,但試試這個:

var arrayOfRandomNums = []; 

function maxInstancesInArray(arr, val) { 
    var hits = []; 
    for(i = 0; i < arr.length; i++) 
     if (arr[i] === val) 
      indexes.push(i); 
    return indexes.length > 2; 
} 

if(!maxInstancesInArray(arrayOfRandomNums, randomNum) { 
    arrayOfRandomNums.push(randomNum); 
} 

如果有該函數將返回true 3或數組中已有更多的傳入數字實例,因此您可以使用它來定義是否將下一個數組推入數組。

0

我做了一個jsFiddle,可以幫助。這個想法是,不要試圖每次都得到rundom數字並檢查,以獲得數組中可用數字的列表,並隨機選擇該數組的索引。

https://jsfiddle.net/m8ohmxmb/

function randNumber(maxRange,maxOccurrencies, resultArrayLenght) { 
    var num = []; 
    var occ = []; 
    var result = []; 
    var randElem; 

    for (var i = 0; i < maxRange; i++) { 
     num.push(i + 1); 
     occ.push(0); 
    } 

    for(i = 0; i < resultArrayLenght; i++) { 
     randElem = Math.floor(Math.random() * num.length); 
     occ[randElem] = occ[randElem] + 1; 
     result.push(num[randElem]); 
     if(occ[randElem] === maxOccurrencies) { 
      occ.splice(randElem,1); 
      num.splice(randElem,1); 
     } 
    } 
    return result; 
    } 
+0

感謝所有的幫助,我現在修復了它,我只是使用indexOf並循環訪問我的數組,直到它匹配indexOf元素。 –

+0

例如:在一個do循環中使用一個if語句如下:if randomNumber == 1 && this.array.indexOf(1)!= - 1然後這將會將do循環開始時設置的變量更改爲true –

0

這是爲保持insertet值及其數的臨時對象一個直接的方法。

function push(n) { 
 
    if (count.full && count[n] === 2) { 
 
     alert('can not insert ' + n); 
 
     return; 
 
    } 
 
    array.push(n); 
 
    count[n] = (count[n] || 0) + 1; 
 
    if (count[n] === 3) { 
 
     count.full = true; 
 
    } 
 
} 
 

 
var array = [], 
 
    count = {}; 
 

 
[4, 3, 4, 4, 7, 8, 8, 8, 9].forEach(push); 
 
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');

相關問題