Created
January 11, 2022 15:51
-
-
Save oderayi/ff0ad2bde67f4547e4f0865984afe841 to your computer and use it in GitHub Desktop.
Trailer Allocation
This file contains 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
const assert = require('assert').strict | |
const allocateTrailers = (carLengths, trailerLength) => { | |
let remainder = trailerLength; | |
const trailers = []; | |
let used = 0 | |
while (used < carLengths.length) { | |
remainder = trailerLength; | |
const trailer = []; | |
for (let i = 0; i < carLengths.length; i++) { | |
if (carLengths[i] != null && carLengths[i] <= remainder) { | |
trailer.push(i); // push index of the car into the trailer journal to identify the car | |
remainder = remainder - carLengths[i]; | |
carLengths[i] = null; | |
used++; | |
if (remainder <= 0) break; | |
} else if (carLengths[i] > trailerLength) { | |
carLengths[i] = null; | |
used++; | |
} | |
} | |
trailers.push(trailer); | |
} | |
return trailers; | |
} | |
// Tests | |
assert.deepEqual(allocateTrailers([5, 5], 10), [[0,1]]); | |
assert.deepEqual(allocateTrailers([5, 5, 5, 3, 90], 10), [[0,1], [2,3]]); | |
console.log(allocateTrailers(Array(100).fill(5), 15)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment