var arr = [1,2,3,4,5,6,7,8,9]
function a(arr,count){
arr = arr || []
count = count || 1
if(!Array.isArray(arr) || isNaN(count)){
alert('')
return false
}
arr.sort((a,b)=>Math.random() - 0.5)
var newarr = []
while(count){
var l = (arr.length/count).toFixed(0)
newarr.push(arr.splice(0,l))
count --
}
return newarr
}
a(arr,4)
there is a flaw here, that is, 9 elements. If you output 4 elements, the number of child elements is fixed to 2, 2, 3, 2, which is related to the algorithm of (arr.length/count) .tofixed (0)
. How to optimize it? you can think about it for yourself
.
function trans (arr, length) {
if (length === 0) return null
let order = [...Array(length).keys()]
let result = order.map(i => [])
let cur = 0
while (arr.length) {
let i = Math.floor(Math.random() * arr.length) //
result[curPP].push(arr.splice(i, 1)[0])
cur %= length
}
//
//
let order1 = []
while (order.length) {
let i = Math.floor(Math.random() * order.length)
order1.push(order.splice(i, 1)[0])
}
return order1.map(i => result[i])
}
trans( [1, 2, 3, 4, 5, 6, 7, 8, 9], 4)
this problem for loop nesting can complete the outer loop bad writing for (var i = 0; I < 4; i PP) means to loop only four times, the inner loop specifically push your number into it, and then the outer loop creates a new array of bad push each time the outer loop ends
well, all javascript,. I'll have a java version
.
/**
*
* @param arr
* @param m
* @return
*/
private static int[][] Test(int[] arr, int m) {
//
if (arr==null || m > arr.length)
return null;
else {
int[][] result = new int[m][];
int everyArrCount = arr.length / m; //
for (int i = 0; i < m; iPP) {
int count = 0;
//
if (i!=m-1) {
count = everyArrCount;
}
else {
count = arr.length-everyArrCount*i;
}
result[i] = new int[count];
for (int j = 0; j < count; jPP) {
result[i][j] = arr[i*everyArrCount+j];
}
}
return result;
}
}