Created
August 11, 2025 17:36
-
-
Save kirkegaard/de28f2cc9de06bc9bfb8c1ff15d8f661 to your computer and use it in GitHub Desktop.
@cassidoo mailing list question
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// To find the optimal groups we can use bin packing. | |
// https://en.wikipedia.org/wiki/Bin_packing_problem | |
const files = [120, 90, 60, 150, 80]; | |
const maxDuration = 200; | |
function groupAudioFiles(files, maxDuration) { | |
// Sort files in descending order | |
const sorted = [...files].sort((a, b) => b - a); | |
// Track groups of files and their current total durations | |
const groups = []; | |
const sums = []; | |
// Process each file, starting with the largest | |
for (const file of sorted) { | |
// Index of best fitting group | |
let bestIdx = -1; | |
// Track minimum remaining space | |
let minSpace = maxDuration + 1; | |
// Find the group with least remaining space that can still fit this file | |
for (let i = 0; i < sums.length; i++) { | |
// Remaining capacity | |
const space = maxDuration - sums[i]; | |
if (space >= file && space < minSpace) { | |
bestIdx = i; | |
minSpace = space; | |
} | |
} | |
// Add to best fitting group or create new group if none fit | |
bestIdx >= 0 | |
? (groups[bestIdx].push(file), (sums[bestIdx] += file)) | |
: (groups.push([file]), sums.push(file)); | |
} | |
return groups; | |
} | |
console.log(groupAudioFiles(files, maxDuration)); | |
console.log(groupAudioFiles(files, 160)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment