#import <Foundation/Foundation.h>
//服务端返回{1,2,3,5,6}时,显示“周一至周三、周五、周六”;
//服务端返回{1,2,5,6}时,显示“周一、周二、周五、周六”;
//服务端返回{1,2,3,4,7}时,显示“周一至周四、周日”。
//服务端返回{1,2,3,4,5, 6, 7}时,显示“周一至周四、周日”。
//服务端返回{1,2,3,4,5, 6, 7}时,显示“周一至周日”。
void getConvertedWeekDayFromNumArr(NSArray<NSNumber *> *numArray) {
static NSDictionary *dictM = nil;
if (!dictM) {
dictM = @{@1: @"周一",
@2: @"周二",
@3: @"周三",
@4: @"周四",
@5: @"周五",
@6: @"周六",
@7: @"周日",
};
}
NSMutableArray<NSString *> *arrM = NSMutableArray.array;
// 如周一至周三,那么`firstValue`就是周一,`lastValue`就是周三
__block int firstValue = 0, lastValue = 0;
// 判断是否连续,如当前周三,那么上一个数字就是周二
__block BOOL isSequence = NO;
// 如周一至周三,那么`startIndex` = 周一的索引数, `endIndex` = 周三的索引数
__block NSUInteger startIndex, endIndex = NSNotFound;
// 记录`startIndex`和`endIndex`, 周一至周三、周五至周日,需要数组记录两对数字,0-2和 4-6
NSMutableArray<NSString *> *indexArrM = NSMutableArray.array;
[numArray enumerateObjectsUsingBlock:^(NSNumber *curNum, NSUInteger idx, BOOL *stop) {
if (idx == 0) {
firstValue = curNum.intValue;
}
int curValue = curNum.intValue;
BOOL isBeforeSequence = isSequence,
// 最后一个元素说明都是`周一、周二、周三、周四、周五、周六、周日`连着的也要考虑到
isAlwaysSequence = isBeforeSequence && isSequence && idx == numArray.count - 1;
isSequence = (curValue - lastValue == 1);
if (isSequence && (curValue - firstValue >= 2)) {
startIndex = [numArray indexOfObject:@(firstValue)];
endIndex = idx;
}
if ((isBeforeSequence && !isSequence && startIndex != NSNotFound && endIndex != NSNotFound)
|| isAlwaysSequence) {
[indexArrM addObject:[@[@(startIndex), @(endIndex)] componentsJoinedByString:@"-"]];
firstValue = curValue;
}
[arrM addObject:dictM[curNum]];
lastValue = curValue;
}];
// NSEnumerationReverse是为了数组越界
[indexArrM enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(NSString *str, NSUInteger idx, BOOL * _Nonnull stop) {
NSArray<NSString *> *indexs = [str componentsSeparatedByString:@"-"];
startIndex = indexs.firstObject.intValue;
endIndex = indexs.lastObject.intValue;
NSString *startStr = arrM[startIndex], *endStr = arrM[endIndex];
[arrM removeObjectsInRange:NSMakeRange(startIndex, endIndex - startIndex + 1)];
[arrM insertObject:[NSString stringWithFormat:@"%@至%@", startStr, endStr] atIndex:startIndex];
}];
NSLog(@"arrM: %@", [arrM componentsJoinedByString:@"、"]);
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
//{1,2,3,5,6}时,显示“周一至周三、周五、周六”;
getConvertedWeekDayFromNumArr(@[@1, @2, @3, @5, @6]);
//服务端返回{1,2,5,6}时,显示“周一、周二、周五、周六”;
getConvertedWeekDayFromNumArr(@[@1, @2, @5, @6]);
//服务端返回{1,2,3,4,7}时,显示“周一至周四、周日”。
getConvertedWeekDayFromNumArr(@[@1, @2, @3, @4, @7]);
//服务端返回{1,2,3,5, 6, 7}时,显示“周一至周三、周五至周日”。
getConvertedWeekDayFromNumArr(@[@1, @2, @3, @5, @6, @7]);
//服务端返回{1,2,3,4,5, 6, 7}时,显示“周一至周日”。
getConvertedWeekDayFromNumArr(@[@1, @2, @3, @4, @5, @6, @7]);
}
return 0;
}
网友评论