时间以半点为单位相连的算法

36次阅读

共计 2036 个字符,预计需要花费 6 分钟才能阅读完成。

背景
在做广点通信息流数据获取的时候有这么一个字段:time_series 投放时间段,格式为 48 * 7 位字符串,且都为 0 和 1,以半个小时为最小粒度,从周一零点开始至周日 24 点结束。0 为不投放,1 为投放,全传 1 视为全时段投放,不允许全部传 0。朋友圈广告的投放时间需大于等于 6 小时,小于等于 30 个自然日,且每天投放的时段需保持一致。在实际的数据获取返回结果为:
000000000000001111111111111000000011111111111111000000000000001111111111111000000011111111111111000000000000001111111111111000000011111111111111000000000000001111111111111000000011111111111111000000000000001111111111111000000011111111111111000000000000001111111111111000000011111111111111000000000000001111111111111000000011111111111111
需求方提出需要将此字段进行格式化,格式化后的字段格式为:
[1, 2, 3, 4, 5, 6, 7]7:00-13:30,17:00-24:00

方法
由于时间比较紧促,简单写了个方法记录下,后面再回来
private String formatTimeSeries(String timeSeries)
{
Map<Integer, List<String>> weekTimeMap = new LinkedHashMap<>();
if(!timeSeries.matches(“[0-1]{336}”)) {
return “”;
}
for (int i = 0; i < timeSeries.length(); i++) {
if(!String.valueOf(timeSeries.charAt(i)).equals(“1″)) {
continue;
}
int day = i/48 + 1;
List<String> list = weekTimeMap.get(day);
if(null == list) {
list = new ArrayList<>();
}
list.add((i%48)/2+(i%48%2==1?”:30″:”:00″));
weekTimeMap.put(day,list);
}
Map<String, List<Integer>> timeWeekMap = new HashMap<>();
for(Integer i : weekTimeMap.keySet()){
List<String> list = weekTimeMap.get(i);
String formatTimeSeries = “”;
while (list.size() > 0) {
String startTime = list.get(0);
list.remove(0);
String startHour = startTime.split(“:”)[0];
String startMinute = startTime.split(“:”)[1];
String endTime = startMinute.equals(“30”) ? (Integer.valueOf(startHour) + 1) + “:00” : startHour + “:30”;
while (list.contains(endTime)) {
list.remove(endTime);
String endHour = endTime.split(“:”)[0];
String endMinute = endTime.split(“:”)[1];
endTime = endMinute.equals(“30”) ? (Integer.valueOf(endHour) + 1) + “:00” : endHour + “:30”;
}
formatTimeSeries += (formatTimeSeries.length() == 0 ? “” : “,”) + startTime + “-” + endTime;
}
List<Integer> timeList = timeWeekMap.get(formatTimeSeries);
if(null == timeList) {
timeList = new ArrayList<>();
}
timeList.add(i);
timeWeekMap.put(formatTimeSeries, timeList);
}
String formatTimeSeries = “”;
for(String time : timeWeekMap.keySet()){
formatTimeSeries += (formatTimeSeries.length() == 0 ? “” : “;”) + timeWeekMap.get(time).toString() + time;
}
return formatTimeSeries;
}

正文完
 0