由於您沒有爲每個數組指定最小數組數或最小/最大元素,因此這裏有一個通用函數,您可以爲每個數組指定最小/最大元素。但請注意,這並不嚴格執行最小元素,事實上它可能不可能達到100%,這取決於原始數組中有多少個元素,以及隨機分配給每個數組元素的數量。例如,如果你有10個元素的原始,你做最小2最大4,你可能會最終3/3/3/1,因爲最低限度將執行,直到沒有足夠的執行。你並沒有真正給出任何「規則」。
min
和max
都是可選的,默認爲1。如果只指定min
,max
將默認爲min
。
還指出,由於數組是通過引用傳遞的,因此默認情況下會將原始數組「空出」。如果要保留原始數組,請取消註釋該函數中的第一行(如果選擇原型,則顯然不適用)。
function randChunkSplit(arr,min,max) {
// uncomment this line if you don't want the original array to be affected
// var arr = arr.slice();
var arrs = [],size=1;
var min=min||1;
var max=max||min||1;
while (arr.length > 0) {
size = Math.min(max,Math.floor((Math.random()*max)+min));
arrs.push(arr.splice(0, size));
}
return arrs;
}
例子
var letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
// randChunkSplit(letters)
[["a"], ["b"], ["c"], ["d"], ["e"], ["f"], ["g"], ["h"], ["i"], ["j"], ["k"], ["l"], ["m"], ["n"], ["o"], ["p"], ["q"], ["r"], ["s"], ["t"], ["u"], ["v"], ["w"], ["x"], ["y"], ["z"]]
// randChunkSplit(letters,3)
[["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"], ["j", "k", "l"], ["m", "n", "o"], ["p", "q", "r"], ["s", "t", "u"], ["v", "w", "x"], ["y", "z"]]
// randChunkSplit(letters,1,3)
[["a"], ["b", "c"], ["d", "e"], ["f", "g", "h"], ["i", "j", "k"], ["l"], ["m"], ["n", "o"], ["p", "q"], ["r"], ["s", "t"], ["u", "v", "w"], ["x", "y", "z"]]
// randChunkSplit(letters,2,3)
[["a", "b", "c"], ["d", "e", "f"], ["g", "h"], ["i", "j", "k"], ["l", "m", "n"], ["o", "p", "q"], ["r", "s", "t"], ["u", "v", "w"], ["x", "y", "z"]]
// randChunkSplit(letters,2,3)
// same thing as before, but notice how this time we end up with just 1 elem left over
[["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"], ["j", "k", "l"], ["m", "n", "o"], ["p", "q"], ["r", "s"], ["t", "u", "v"], ["w", "x", "y"], ["z"]]
或者,你可以把它的原型到陣,如果你想,這樣的事情:
Array.prototype.randChunkSplit = function (min,max) {
var arrs = [],size=1;
var min=min||1;
var max=max||min||1;
while (this.length > 0) {
size = Math.min(max,Math.floor((Math.random()*max)+min));
arrs.push(this.splice(0, size));
}
return arrs;
}
var letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
letters.randChunkSplit(1,4)
是否有一定數量的組想要將數組拆分成幾組? – Schickmeister
每個組中還有最小最大元素數量? –
是否有任何規則如何將它們分成組的數量和大小? –