高效生成循环移位式固定块数组的逻辑实现及模式名称确认
1. Corrected & Efficient Implementation
First, let's fix the logic to generate the required set of arrays and store them in an object. The key issue with your original splice approach is that it modifies the array in-place incorrectly when the WO block wraps around the end of the array. Instead, we can use modular arithmetic to cleanly calculate the positions of the 'WO' entries for each shift, which is both efficient and easy to understand.
Here's the complete implementation:
// Generates a single shift array with 3 'WO's and 4 'M's, shifted by the given offset function generateShiftArray(offset, totalDays = 7, woCount = 3, defaultShift = 'M') { // Initialize array with all default shifts const shiftArr = Array(totalDays).fill(defaultShift); // Calculate positions for 'WO' using modulo to handle wrap-around for (let i = 0; i < woCount; i++) { const position = (offset + i) % totalDays; shiftArr[position] = 'WO'; } return shiftArr; } // Generates the full object of shift arrays with unique keys function generateShiftObject() { const shiftMap = {}; // Use unique keys (a-g) for each shift variant const keys = ['a', 'b', 'c', 'd', 'e', 'f', 'g']; keys.forEach((key, index) => { shiftMap[key] = generateShiftArray(index); }); return shiftMap; } // Example usage const finalShiftObject = generateShiftObject(); console.log(finalShiftObject);
Why this works:
- Efficiency: Each array is generated in O(n) time (n = total days), and with 7 total arrays, the overall time complexity is O(49) — negligible for this use case.
- Wrap-around handling: The modulo operator
%ensures that when the WO block reaches the end of the array, it wraps around to the start automatically (e.g., offset 5 places WO at positions 5,6,0). - Maintainability: The code is modular, so you can easily adjust the number of WO days, total days, or default shift by modifying the function parameters.
Note: Your example had duplicate keys (e.g., two 'b' entries), which is invalid in JavaScript objects. This implementation uses unique keys from 'a' to 'g' to avoid that issue.
2. Pattern Name Identification
Yes, this pattern can be classified as a variant of Round Robin (循环轮询). Specifically, it's a Circular Shift Round Robin pattern:
- The core idea of Round Robin is to cycle through options in a repeating sequence, which matches how we're shifting the WO block's position across each array.
- The "circular shift" part refers to how the WO block wraps around the end of the array to the start, maintaining the continuous cycle.
In short, calling this a Round Robin pattern is accurate and widely understood in programming and scheduling contexts.
内容的提问来源于stack exchange,提问作者sourav kumar

