【问题标题】:Logic for filling empty space with different sizes of boxes用不同大小的盒子填充空白空间的逻辑
【发布时间】:2020-11-30 06:56:31
【问题描述】:

我有一个逻辑问题。
我有一个起点 A 和终点 B。我有不同尺寸的块(42、21)英寸和一个可变尺寸的填充盒(可以从 7-26 英寸延伸)。我需要填充空间以适应最大尺寸的块,然后剩余的空间由填充框填充。

例如 a) 如果间隙是 50 英寸,我会放一个 42 英寸的块和一个填充盒 (42 + 8*)

b) 如果间隙是 43 英寸,我不能放置 42 英寸的积木,因为剩余的间隙是 1 英寸,我没有东西可以放进去。所以我将放置一个 21 英寸的块,填充块将占据 22 英寸的其余部分,因为它可以伸展到 26 英寸。 ( 21 + 22*)

c) 很少有像 48 这样的例外 - 不适合上述规则集。但我们可以忽略这些,因为差距很少是 48 或 27。如果是,它会留下一个差距,没关系。

【问题讨论】:

  • 我们不能使用多个填充框吗?

标签: javascript algorithm logic


【解决方案1】:

假设只能有一个填充框,这应该可以解决问题。

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));

【讨论】:

    猜你喜欢
    • 2010-10-26
    • 2021-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多