84 lines
2.8 KiB
Java
84 lines
2.8 KiB
Java
|
package com.bjtds.brichat.util;
|
|||
|
|
|||
|
import java.util.*;
|
|||
|
import java.util.regex.Matcher;
|
|||
|
import java.util.regex.Pattern;
|
|||
|
|
|||
|
public class TrainUtils {
|
|||
|
|
|||
|
/***
|
|||
|
* 列车号转车厢
|
|||
|
* @param trainNo
|
|||
|
* @return
|
|||
|
*/
|
|||
|
public static Map<String, String> convertTrainNo(String trainNo) {
|
|||
|
// 1. 提取前缀后的数字部分
|
|||
|
Pattern pattern = Pattern.compile("(\\d+)$");
|
|||
|
Matcher matcher = pattern.matcher(trainNo);
|
|||
|
|
|||
|
if (!matcher.find()) {
|
|||
|
throw new IllegalArgumentException("无法在前缀 '" + trainNo + "' 中找到数字");
|
|||
|
}
|
|||
|
int i = Integer.parseInt(matcher.group(1));
|
|||
|
|
|||
|
// 2. 计算三个基础编号
|
|||
|
int code1 = 3 * (i - 1) + 1;
|
|||
|
int code2 = code1 + 1;
|
|||
|
int code3 = code1 + 2;
|
|||
|
|
|||
|
// 格式化为三位数
|
|||
|
String code1Str = String.format("%03d", code1);
|
|||
|
String code2Str = String.format("%03d", code2);
|
|||
|
String code3Str = String.format("%03d", code3);
|
|||
|
|
|||
|
// 3. 组装九个车厢号
|
|||
|
List<String> part1 = Arrays.asList("D" + code1Str, "P" + code1Str, "M" + code1Str);
|
|||
|
List<String> part2 = Arrays.asList("M" + code2Str, "P" + code2Str, "F" + code2Str);
|
|||
|
List<String> part3 = Arrays.asList("M" + code3Str, "P" + code3Str, "D" + code3Str);
|
|||
|
|
|||
|
// 合并结果
|
|||
|
List<String> allParts = new ArrayList<>();
|
|||
|
allParts.addAll(part1);
|
|||
|
allParts.addAll(part2);
|
|||
|
allParts.addAll(part3);
|
|||
|
|
|||
|
// 转换为逗号分隔字符串
|
|||
|
String result = String.join(", ", allParts);
|
|||
|
|
|||
|
return Collections.singletonMap("result", result);
|
|||
|
}
|
|||
|
|
|||
|
/*
|
|||
|
* 将车厢号转换为列车号
|
|||
|
* @param carriageNumber 车厢号(例如 "D109")
|
|||
|
* @return 列车号(例如 "RT37")
|
|||
|
*/
|
|||
|
public static String convertToTrainNo(String carriageNumber) {
|
|||
|
// 1. 提取数字部分并验证格式
|
|||
|
Matcher matcher = Pattern.compile("\\d+").matcher(carriageNumber);
|
|||
|
if (!matcher.find()) {
|
|||
|
throw new IllegalArgumentException("无效的车厢号格式: " + carriageNumber);
|
|||
|
}
|
|||
|
int n = Integer.parseInt(matcher.group());
|
|||
|
|
|||
|
// 2. 计算行号 i
|
|||
|
int i = (n + 2) / 3; // 等效于 (n - 1)/3 + 1
|
|||
|
|
|||
|
// 3. 验证行号范围
|
|||
|
if (i < 1 || i > 37) {
|
|||
|
throw new IllegalArgumentException("行号超出有效范围 1-37");
|
|||
|
}
|
|||
|
|
|||
|
// 4. 验证数字是否符合规则
|
|||
|
int expectedCode1 = 3 * (i - 1) + 1;
|
|||
|
int expectedCode2 = expectedCode1 + 1;
|
|||
|
int expectedCode3 = expectedCode1 + 2;
|
|||
|
if (n != expectedCode1 && n != expectedCode2 && n != expectedCode3) {
|
|||
|
throw new IllegalArgumentException("数字 " + n + " 不符合编码规则");
|
|||
|
}
|
|||
|
|
|||
|
// 5. 组合列车号(假设前缀为 RT)
|
|||
|
return "TS" + i;
|
|||
|
}
|
|||
|
}
|