Logic for filling empty space with different sizes of boxes

Viewed 202

I have a logical problem.
I have a starting point A and ending point B. I have different sizes of blocks (42, 21) inches and a variable size filler box (can stretch from 7-26) inches. I need to fill the space so that the maximum size blocks are fit and then the remaining space is filled by the filler box.

for eg a) if the gap is 50 inches, I will put a 42-inch block and a filler box ( 42 + 8*)

b) if the gap is 43 inches, I cannot put a 42-inch block because the remaining gap is 1 inch and I have nothing to fit in it. so I will put a 21-inch block and the filler block will take the rest of the 22 inches as it can stretch to 26 inches. ( 21 + 22*)

c) there are few exceptions like 48 - which cannot fit in the above rule set. but we can ignore those as the gap will rarely be 48 or 27. If it is, it will leave a gap and that is okay.

1 Answers

Assuming that there can be only one filler box, this should do the trick.

function fill_space(space) {
  const small_block = 21;
  const big_block = 2 * small_block;
  const min_filler = 7;
  const max_filler = 26;
  if (space % small_block == 0) {
    const num_big = Math.trunc(space / big_block);
    const num_small = (space - num_big * big_block) / small_block;
    return { num_big: num_big, num_small: num_small, filler: 0 };
  }
  if (space < min_filler) {
    return { num_big: 0, num_small: 0, filler: 0 };
  }
  const max_block_space = space - min_filler;
  const num_big = Math.trunc(max_block_space / big_block);
  const max_small_space = max_block_space - num_big * big_block;
  const num_small = Math.trunc(max_small_space / small_block);
  const filler = Math.min(
    min_filler + max_small_space - num_small * small_block,
    max_filler
  );
  return { num_big: num_big, num_small: num_small, filler: filler };
}

console.log(fill_space(0));
console.log(fill_space(6));
console.log(fill_space(21));
console.log(fill_space(42));
console.log(fill_space(48));
console.log(fill_space(50));
console.log(fill_space(63));
Related