package com.maya.test; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; public class RandomSelect { public static void main(String[] args) { String[] names = { "郇", "王", "焦", "劉", "尹", "呂", "鞏", "董", "白", "朱", "封", "郭", "班", "楊"}; List<List<String>> gl = getGroup(names, 3); if(gl != null) { for (List<String> l : gl) { System.out.println(l); } } } /** * 獲取隨機數 */ public static int getRandom(int i) { Random r = new Random(); return r.nextInt(i); } /** * 進行分組 els 需要進行分組的成員 groups 需要分成幾組 */ public static List<List<String>> getGroup(String[] els, int groups) { // 判斷驗證 if (els.length < (groups * 2)) { System.out.println("分組數過多! 最多只能分" + (els.length / 2) + "組"); return null; } if (groups == 1) { System.out.println("分組數不能為1組"); return null; } // 數據源的list List<String> list = new ArrayList<String>(); // 作為結果返回的list List<List<String>> groupsList = new ArrayList<List<String>>(); // List<Map<String, String>> groupsList = new ArrayList<List<String>>(); // 往數據源里面添加數據 for (int i = 0; i < els.length; i++) { list.add(els[i]); } // 隨機打亂一下順序 Collections.shuffle(list); // 計算一下每組多少人 int peoples = els.length / groups; // 分組開始 for (int i = 0; i < groups; i++) { List<String> group = new ArrayList<String>(); for (int j = 0; j < peoples; j++) { int random = getRandom(list.size()); group.add(list.get(random)); list.remove(random); } groupsList.add(group); } // 最后剩下的人再重新分配一遍 for (int i = 0; i < list.size(); i++) { groupsList.get(i).add(list.get(i)); } return groupsList; } }
這個隨即分組的思想可以在很多地方運用