Skip to content

Instantly share code, notes, and snippets.

@oderayi
Created January 11, 2022 15:51
Show Gist options
  • Save oderayi/ff0ad2bde67f4547e4f0865984afe841 to your computer and use it in GitHub Desktop.
Save oderayi/ff0ad2bde67f4547e4f0865984afe841 to your computer and use it in GitHub Desktop.
Trailer Allocation
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