Algorithm: Divide the 24 hours a day into 48 segments per half hour

Divide the 24 hours a day into 48 segments per half hour. We use a bitmap to represent the selected time interval. For example 110000000000000000000000000000000000000000000000, it means that the first half hour and the second half hour are selected, and the rest of the time periods are not selected. It corresponds to the time interval of 00:00~01:00. A bitmap may have multiple discrete time intervals selected, for example 110010000000000000000000000000000000000000000000, it means that the two time intervals 00:00-1:00 and 02:00-02:30 are selected.

Requirement: Write a function timeBitmapToRanges to convert the time bitmap described by the above rules into an array of selected time intervals.
Sample input: "110010000000000000000000000000000000000000000000"
Sample output:["00:00~01:00", "02:00~02:30"]


function timeBitmapToRanges(timeBitmap) {
    
    
	// 转化格式
	function format(start, end) {
    
    
	    let endHour = (end / 2).toFixed(1);
	    let startHour = (start / 2).toFixed(1);
	    let reg = /(\d+)\.(\d+)/;
	    const endRes = endHour.match(reg);
	    const startRes = startHour.match(reg);
	    return (
	        addZero(startRes[1]) +
	        ':' +
	        addZero(startRes[2]) +
	        '~' +
	        addZero(endRes[1]) +
	        ':' +
	        addZero(endRes[2])
	    );
	}
	function addZero(num) {
    
    
	    num = num === '5' ? '30' : num;
	    return num.length > 1 ? num : '0' + num;
	}
    let timeArr = timeBitmap.split('').map(v => +v);
    const res = [];
    let range = {
    
    };
    let start = 0;
    for (let i = 0; i <= timeArr.length; i++) {
    
    
        if (timeArr[i]) {
    
    
            start++;
        }
        if (!timeArr[i] && timeArr[i - 1]) {
    
    
            range[i] = start;
            start = 0;
        }
    }
    for (let j in range) {
    
    
        res.push(format(parseInt(j - range[j]), parseInt(j)));
    }
    return res;
}
 
console.log(
 timeBitmapToRanges('110010000000000000001110000000000000000000000111')
);
// [ '00:00~01:00', '02:00~02:30', '10:00~11:30', '22:30~24:00' ]

Guess you like

Origin blog.csdn.net/weixin_43972437/article/details/114015025