# 遇到两次的笔试题：求连续区间

·  阅读 4254

## 第一道题的题解

``````function calcContinuousRanges(arr) {
let continuousRanges = [];
let index = 0;
while(index < arr.length) {
const range = {
start: arr[index],
end: arr[index]
};
continuousRanges.push(range);
index++;
}
}

``````function calcContinuousRanges(arr) {
let continuousRanges = [];
let index = 0;
while( index < arr.length) {
const range = {
start: arr[index],
end: arr[index]
};
while (index < arr.length && arr[index + 1] === arr[index] + 1) {
range.end = arr[index + 1];
index++;
}
continuousRanges.push(range);
index++;
}
console.log(JSON.stringify(continuousRanges));
}

``````calcContinuousRanges([1,2,3,5,7,8,10]);

``````const formatted = continuousRanges.map(({start, end}) => {
return start === end ? start : `\${start}~\${end}`;
}).join(' ');

``````function calcContinuousRanges(arr) {
let continuousRanges = [];
let index = 0;
while( index < arr.length) {
const range = {
start: arr[index],
end: arr[index]
};
while (index < arr.length && arr[index + 1] === arr[index] + 1) {
range.end = arr[index + 1];
index++;
}
continuousRanges.push(range);
index++;
}
// console.log(JSON.stringify(continuousRanges));
const formatted = continuousRanges.map(({start, end}) => {
return start === end ? start : `\${start}~\${end}`;
}).join(' ');
console.log(formatted);
}

calcContinuousRanges([1,2,3,5,7,8,10]);

## 第二道题的题解

``````function timeBitmapToRanges(timeBitmap) {
let index = 0;
let ranges = [];
while(index < timeBitmap.length) {
if (timeBitmap[index] === '0') {
index++;
continue;
}
let curRange = { start: index, end: index};
while (timeBitmap[index] === '1') {
curRange.end = index;
index++;
}
ranges.push(curRange);
}
}

``````ranges.map(range => {
let str = 0;
return format(range.start * 0.5) + '~' + format(range.end * 0.5 + 0.5);
});

``````function format(num) {
const left = Math.floor(num);
const leftStr =   left < 10 ? '0' + left : left;
const right = num % 1 === 0.5 ? 30 : 0;
const rightStr =   right < 10 ? '0' + right : right;
return leftStr + ':' + rightStr;
}

``````function timeBitmapToRanges(timeBitmap) {
let index = 0;
let ranges = [];
while(index < timeBitmap.length) {
if (timeBitmap[index] === '0') {
index++;
continue;
}
let curRange = { start: index, end: index};
while (timeBitmap[index] === '1') {
curRange.end = index;
index++;
}
ranges.push(curRange);
}

return ranges.map(range => {
let str = 0;
return format(range.start * 0.5) + '~' + format(range.end * 0.5 + 0.5);
});
}

function format(num) {
const left = Math.floor(num);
const leftStr =   left < 10 ? '0' + left : left;
const right = num % 1 === 0.5 ? 30 : 0;
const rightStr =   right < 10 ? '0' + right : right;
return leftStr + ':' + rightStr;
}

console.log(timeBitmapToRanges('110010000000000000000000000000000000000000000000'))