题目:
以下格式 2013-10-01~2013-10-02 100表示2013-10-01入住,2013-10-02离店,入住一天的价格是¥100。
现有文件中包含多行这样的日期价格段,请将其合并,合并的规则包括:
1)价格相同,日期段相邻或者重叠的需要合并
2)相同日期的价格已后面录入的为准
例子1:
2013-08-01~2013-08-31 300
2013-08-25~2013-09-30 300
合并后就是
2013-08-01~2013-09-30 300
例子2:
2013-08-01~2013-12-31 300
2013-10-01~2013-10-07 500
合并之后就是
2013-08-01~2013-09-30 300
2013-10-01~2013-10-07 500
2013-10-08~2013-12-31 300
请读入指定文件price.txt文件如下
2013-08-01~2013-08-31 300
2013-08-25~2013-09-30 300
2013-08-01~2013-12-31 300
2013-10-01~2013-10-07 500
2013-01-20~2013-02-25 300
2013-01-01~2013-02-05 500
2014-08-01~2014-08-31 300
2014-09-01~2014-09-30 300
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.google.common.base.Charsets;
import com.google.common.collect.Range;
import com.google.common.collect.RangeMap;
import com.google.common.collect.TreeRangeMap;
import com.google.common.io.Files;
public class DateMerge {
private final static String pricefile = "./source/price.txt";
public static void processPrice() throws IOException, ParseException{
List<String> lines = Files.readLines(new File(pricefile), Charsets.UTF_8);
RangeMap<Date, Integer> rangeMap = TreeRangeMap.create();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
for(String line: lines){
line = line.trim();
if(line.equals("")) continue;
String [] items = line.split(" ");
String [] dates = items[0].split("~");
Date s = format.parse(dates[0]),
e = format.parse(dates[1]);
Date bs = new Date(s.getTime()-24*3600*1000),
ae = new Date(e.getTime()+24*3600*1000);
int value = Integer.parseInt(items[1]);
Entry<Range<Date>, Integer> entryS = rangeMap.getEntry(bs),
entryE = rangeMap.getEntry(ae);
if(entryS!=null&&entryS.getValue().equals(value)){
rangeMap.remove(entryS.getKey());
s = entryS.getKey().lowerEndpoint();
}
if(entryE!=null&&entryE.getValue().equals(value)){
rangeMap.remove(entryE.getKey());
e = entryE.getKey().upperEndpoint();
}
rangeMap.put(Range.closed(s, e), value);
}
Map<Range<Date>, Integer> rangeDateMap = rangeMap.asMapOfRanges();
Set<Entry<Range<Date>, Integer>> entries = rangeDateMap.entrySet();
Iterator<Entry<Range<Date>, Integer>> iterator = entries.iterator();
while(iterator.hasNext()){
Entry<Range<Date>, Integer> next = iterator.next();
System.out.println(next.getKey() + "\t" + next.getValue());
}
}
public static void main(String [] args) throws IOException, ParseException{
processPrice();
}
}