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

Posted xiaoyangboke

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了给定一个数组和分组数,写出随机分组算法相关的知识,希望对你有一定的参考价值。

直接上代码:

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)


还有待优化的地方,欢迎指正!
 

以上是关于给定一个数组和分组数,写出随机分组算法的主要内容,如果未能解决你的问题,请参考以下文章

14常见算法数组分组排序

贪心算法-- 纪念品分组

Java 数据分组问题

给定一个单词列表,如何开发一种算法方法来对它们进行语义分组?

给定距离内的点分组算法

随机分组中,区组随机法和分层随机法的区别