【问题标题】:Is it possible to make this more efficient?是否有可能使这更有效?
【发布时间】:2025-12-02 06:00:02
【问题描述】:

我已经编写了一个 Google 表格脚本来计算在给定 x 数量的客户和每瓶 y 数量的情况下需要的瓶子数量。


=BOTTLES_REQUIRED(1,22) #=> 1
=BOTTLES_REQURIED(22,22) #=> 1
=BOTTLES_REQUIRED(23,22) #=> 2

function BOTTLES_REQUIRED(customers, shots_per_bottle) {

  var bottles_required = 1;
  var shots = 0;

  for(var i = 0; i < customers; i++) {
    shots++;

    if( shots > shots_per_bottle ) {
       bottles_required++;
       shots = 0;
    }
  }

   return bottles_required;
}

虽然有时需要运行一段时间,但有没有更有效的编写方式?

【问题讨论】:

  • ??这不就是bottles_required = Math.ceil (customers / shots_per_bottle)吗?
  • 是的,但是你没有得到瓶子里剩下的镜头,但我们可以把它偷偷溜到吧台后面吗?

标签: javascript performance google-sheets google-spreadsheet-api


【解决方案1】:

为什么不使用数学呢?

function BOTTLES_REQUIRED(customers, shots_per_bottle) {
    return Math.ceil(customers / shots_per_bottle);
}

看看这个jsFiddle example

【讨论】:

    最近更新 更多