给定一个数组和分组数,写出随机分组算法

直接上代码:

java:

public class RandomGroup {

public static void main(String[] args) {
String[] team = {"a", "b", "c", "d","e","f", "g", "h", "i","j"};
String[][] result = randomGroup(team, 3);
for (String[] strings : result) {
System.out.println(Arrays.toString(strings));
}

}
public static String[][] randomGroup(String[] team,int num){
int col = team.length/num;
int ys = team.length%num;
if(ys>0)col=col+1;
int a=0,b=0;
String[][] result=new String[num][col];
while (team.length>0){
int index = (int) (Math.random() * team.length);
result[a][b] =team[index];
team[index]=team[team.length-1];
team = Arrays.copyOf(team, team.length-1);
if(a<num-1){
a++;
}else if(b<col-1){
a=0;
b++;
}
}

return result;
}
}

python版:
import random

k = 3
arr = ["a", "b", "c", "d","e","f", "g", "h", "i","j"]
every_len = int(len(arr) / k)
print(every_len)
arr_flag = []
random_num = []
index = 0
for i in range(len(arr)):
arr_flag.append(True)
random_num.append(index)
index += 1

random.shuffle(random_num)

result_arr = []
every_arr = []
index = 0
for i in range(0, len(arr) - 1, every_len):
index += 1
for j in range(every_len):
every_arr.append(arr[random_num[i]])
i += 1
result_arr.append(every_arr)
every_arr = []
if index >= k:
break

for i in range(len(random_num) - len(result_arr) * every_len):
result_arr[i].append(arr[random_num[len(arr) - 1 - i]])

print(result_arr)


还有待优化的地方,欢迎指正!
 
posted @ 2019-07-23 18:29  XiaoyangBoke  阅读(1858)  评论(0编辑  收藏  举报