簡介
本演算法為等級與時間結合計算對應優先順序邏輯
等級越高者優先順序越高
同等級下,時間越小者優先順序越高
實現
主方法
calculatePriority
import com.zk.blog.enums.TypeEnum;
import org.apache.commons.lang3.StringUtils;
/**
* @program:
* @description:
* @author: zk
* @create: 2024-08-09 17:26
**/
public class PriorityService {
/**
* 基線時間
* 2024-01-01 00:00:00
* 秒值
*/
private static final Long baseTime = 1704067200L;
/**
* 字首
*/
private static final String prefix = "1";
/**
* 按照階梯型別+時間計算優先順序
* 型別級別越高、時間越前者優先順序越高
*
* @param type 型別 型別優先順序最大2位
* @param time 計算時間
* @return 優先順序結果 :越大優先順序越高
*/
public String calculatePriority(TypeEnum type, Long time) {
//毫秒轉秒
if (String.valueOf(time).length() == 13) {
time = time / 1000;
}
if (String.valueOf(time).length() != 10) {
throw new RuntimeException("時間格式錯誤");
}
String typePriority = String.valueOf(type.getLevelPriority());
String timePriority = String.valueOf(Integer.MAX_VALUE - (time - baseTime));
typePriority = StringUtils.leftPad(typePriority, 2, "0");
timePriority = StringUtils.leftPad(timePriority, 12, "0");
return new StringBuilder().append(prefix).append(typePriority).append(timePriority).toString();
}
}
採用:
Integer.MAX_VALUE
- (time
-基線時間
)計算出時間優先順序
等級優先順序為2位,不夠則左側補0
時間優先順序為12位,不夠則左側補0
最終優先順序::1位字首
+2位級別優先順序
+12位時間優先順序
=13位字串
等級型別列舉
TypeEnum
/**
* @program:
* @description: 型別級別
* @author: zk
* @create: 2024-08-09 17:30
**/
public enum TypeEnum {
/**
* 級別:描述, 等級優先順序
*/
ONE("一級", 1),
TWO("二級", 2),
THREE("三級", 3),
FOUR("四級", 4),
FIVE("五級", 5),
SIX("六級", 6),
SEVEN("七級", 7),
EIGHT("八級", 8),
NINE("九級", 9),
TEN("十級", 10);
private String name;
private Integer levelPriority;
TypeEnum(String name, Integer levelPriority) {
this.name = name;
this.levelPriority = levelPriority;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getLevelPriority() {
return levelPriority;
}
public void setLevelPriority(Integer levelPriority) {
this.levelPriority = levelPriority;
}
}
測試
- 測試程式碼
@Test
public void test(){
//一級 + 2024-02-01 00:00:00
System.out.println(calculatePriority(TypeEnum.ONE, 1706745600L));
//一級 + 2024-03-01 00:00:00
System.out.println(calculatePriority(TypeEnum.ONE, 1709251200L));
//九級 + 2024-02-01 00:00:00
System.out.println(calculatePriority(TypeEnum.NINE, 1706745600L));
//九級 + 2024-03-01 00:00:00
System.out.println(calculatePriority(TypeEnum.NINE, 1709251200L));
//十級 + 2024-02-01 00:00:00
System.out.println(calculatePriority(TypeEnum.TEN, 1706745600L));
//十級 + 2024-03-01 00:00:00
System.out.println(calculatePriority(TypeEnum.TEN, 1709251200L));
}
- 測試結果
101002144805247
101002142299647
109002144805247
109002142299647
110002144805247
110002142299647
結束