package com.zy.common.model;
import com.alibaba.fastjson.JSON;
import com.core.exception.CoolException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* 立库货架实体类
* Created by vincent on 2020/6/11
*/
public class Shelves {
// 货架排数量
public final int size;
// 货架组数量
public final int group;
// 偏移量[default:0]
public final int offset;
// 货架实例节点集合
public List> nodes;
public Shelves(int size, int group) {
this(size, group, 0);
}
/**
* @param size 货架单排总数
* @param group 货架组数量
* @param offset 序列号偏移量
*/
public Shelves(int size, int group, int offset) {
this.size = size;
this.group = group;
this.offset = offset;
init();
}
/**
* 初始化方法【私有】
*/
private void init(){
if (group == 0 || size%group != 0) {
throw new RuntimeException("shelves init fail!");
}
nodes = new ArrayList<>();
for (int g = 1; g <= this.group; g++){
int unit = size/group;
List node = new ArrayList<>();
for (int i = (g-1)*unit+1+offset ; i <= g*unit+offset; i++){
node.add(i);
}
nodes.add(node);
}
}
/**
* 开始计算 =======>>>
*
* 货架命中规则如下:
* 安装位置: [1] [2] | [3] [4] -------- [5] [6] | [7] [8]
* 命中顺序: 1 -> 5 -> 4 -> 8 -> 2 -> 6 -> 3 -> 7 -> 1 ...
*
* 1.该规则适不限制货架数量,总数与组别在构造器中设置
* 2.如有序列号起始问题,用偏移量规避即可
*
* @param curSeq 当前货架号
* @return 规则命中货架号
*/
public int start(int curSeq){
Iterator> iterator = nodes.iterator();
while (iterator.hasNext()){
List node = iterator.next();
if (node.contains(curSeq)) {
int idx = node.indexOf(curSeq);
// 是否为末尾货架
if (iterator.hasNext()) {
return iterator.next().get(idx);
} else {
List first = nodes.get(0);
int val = first.get(idx);
int res = size / group + 1 + offset - val;
// 反向命中货架时不再是对立下标(相对于巷道)
if (res < val) {
// 轮询所有货架后重新开始定位
if (val - res - offset == 1) {
return first.get(0);
}
res = res + 1;
}
return res + offset;
}
}
}
return -1;
}
public Integer get(Integer curRow) {
for (List node : nodes){
if (node.contains(curRow)) {
return nodes.indexOf(node) + 1;
}
}
throw new CoolException("货排检索系统报错, node:" + JSON.toJSONString(nodes) + ", curRow:" + curRow);
}
public static void main(String[] args) throws InterruptedException {
Shelves shelves = new Shelves(8,2);
System.out.println(shelves.nodes.toString());
int start = 1;
while (true) {
System.out.println(start);
start = shelves.start(start);
Thread.sleep(500L);
}
}
}