java做一個值日生表。要用到連結串列,random,list。一共十三個人,四個人一組,最後剩下一個自己一個集合。不能重複

瓜瓜東西發表於2014-07-28
package com.wanju.project001.zonghe.test;


import java.util.LinkedList;
import java.util.List;
import java.util.Random;


public class TestWork {


public static final int ALL_NUM = 13;
List<Student> ls = new LinkedList<Student>();
List<Student> lsForCopy = new LinkedList<Student>();
List<LinkedList<Student>> lss = new LinkedList<LinkedList<Student>>();


public void init() {
for (int i = 0; i < ALL_NUM; i++) {
Student s = new Student();
s.setNum(i);
s.setName("s" + i);
ls.add(s);
}
}


public static void main(String[] args) {
TestWork t = new TestWork();
t.init();
t.group();
t.show();
}


public void group() {
for (int i = 0; i < 4; i++) {
lss.add(new LinkedList<Student>());
}
boolean flg = true;
Random r = new Random();
StudentHelper helper = new StudentHelper(ls);
helper.setLsForCopy(lsForCopy);
for (int k = 0; k < 4; k++) {


for (int i = 0; i < 4; i++) {


while (flg) {
int v = r.nextInt(ls.size());
if (!helper.checkStudentByNum(v)) {
Student ss = helper.getStudentByNum(v);
lss.get(k).add(ss);
lsForCopy.add(ss);
helper.addLsForCopyStudent(ss);
if (lss.get(k).size() >= 4) {
flg = false;
}
if (k == 3) {
flg = false;
}
break;
}
}
}
flg = true;
}
}


public void show() {
for (int i = 0; i < lss.size(); i++) {
System.out.println(lss.get(i));
}
}
}


class Student {
private int num;
private String name;


public int getNum() {
return num;
}


public void setNum(int num) {
this.num = num;
}


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


@Override
public String toString() {
return "Student [num=" + num + ", name=" + name + "]";
}


}


class StudentHelper {
List<Student> ls = new LinkedList<Student>();
List<Student> lsForCopy = new LinkedList<Student>();


public List<Student> getLsForCopy() {
return lsForCopy;
}


public void setLsForCopy(List<Student> lsForCopy) {
this.lsForCopy = lsForCopy;
}


public void addLsForCopyStudent(Student s) {
lsForCopy.add(s);
}


public StudentHelper() {
}


public StudentHelper(List<Student> ls) {
this.ls = ls;
}


public Student getStudentByNum(int v) {
for (int i = 0; i < ls.size(); i++) {
if (ls.get(i).getNum() == v) {
return ls.get(i);
}
}
return null;
}


public boolean checkStudentByNum(int v) {
return getStudentByNumFromLsForCoby(v) == null ? false : true;
}


public Student getStudentByNumFromLsForCoby(int v) {
for (int i = 0; i < lsForCopy.size(); i++) {
if (lsForCopy.get(i).getNum() == v) {
return lsForCopy.get(i);
}
}
return null;
}


}

相關文章