public static void assignRangeByRatio(Lab lab) { List<Group> groupList = lab.getGroupList(); intcurrent = 0; for (Groupgroup : groupList) { BigDecimal ratio = group.getRatio(); int count = ratio.multiply(range).setScale(0, RoundingMode.HALF_UP).intValue(); int start = current; int end = current + count - 1; group.setStart(start); group.setEnd(end); current = end + 1; } }
public static final int hashCode(String key, String value) { return Math.abs(Objects.hashCode(key) ^ Objects.hashCode(value)); }
接着,使用上面的模型并且结合Hash算法来实现分组.分区函数的返回结果就是某一个分组.
1 2 3 4 5 6 7 8 9 10 11
public static Group partition(String key, Lab lab) { int hashCode = hashCode(key, lab.getName()); int position = hashCode % range.intValue(); List<Group> groupList = lab.getGroupList(); for (Group group : groupList) { if (group.getStart() <= position && group.getEnd() >= position) { return group; } } return null; }
public static void main(String[] args) { Lab subject = new Lab(); Group math = new Group(); math.setRatio(new BigDecimal(0.5)); math.setKey("math"); math.setName("数学");
Group chinese = new Group(); chinese.setRatio(new BigDecimal(0.3)); chinese.setKey("chinese"); chinese.setName("语文");
Group english = new Group(); english.setRatio(new BigDecimal(0.2)); english.setKey("english"); english.setName("英语");