代码之家  ›  专栏  ›  技术社区  ›  rball

如何根据材料长度编程计算数量?

  •  0
  • rball  · 技术社区  · 6 年前

    我正在计算,如果我把一个更大的卷切成多个更小的卷,我可以得到的材料卷的数量。

    例如,如果我有1个25米的卷,我可以把它切成1个15米的卷,2个10米的卷,5个5米的卷。所以我希望我的数量看起来像:

    • 1 25m
    • 1 15m
    • 2万米
    • 5米

    现在,我也可以有其他任何一个的现有数量,如1卷25米,1卷15米和1卷5米,然后它看起来像:

    • 1 25m
    • 2 15m
    • 3万米
    • 9米

          for (let i = 0; i < this.sizes.length; i++) {
          const size = this.sizes[i];
          for (let j = 0; j < this.cart.items.length; j++) {
              const item = this.cart.items[j];
              if (item.sizeId === size.id) {
                  size.quantity -= item.quantity;
              }
              size.amountOfMaterial = size.quantity * size.length;
          }
      }
      

    我设置了第一个循环,以根据他们的购物车中已经存在的内容获得正确的物料数量和数量。我被困在下一部分。

    编辑:下面的答案最终让我想到了这个:

    calculateQuantities() {
        let quantities = {};
        for (let i = 0; i < this.sizes.length; i++) {
            const size = this.sizes[i];
            for (let j = 0; j < this.cart.items.length; j++) {
                const item = this.cart.items[j];
                if (item.sizeId === size.id) {
                    size.quantity -= item.quantity;
                }
            }
            size.actualQuantity = size.quantity;
    
            let counter = 0;
            for (let j = 0; j < this.sizes.length; j++) {
                const otherSize = this.sizes[j];
                counter += Math.floor(otherSize.length * otherSize.quantity / size.length)
            }
            console.log(`${counter} ${size.length}m`);
            quantities[size.length] = counter;
        }
    
        for (let i = 0; i < this.sizes.length; i++) {
            this.sizes[i].quantity = quantities[this.sizes[i].length];
        }
    }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Abid Hasan    6 年前

    如果我误解了这个问题,请告诉我哪里出错了。 我假设25、15、10和5是预先定义的。这是对的吗?我没有在你的问题中看到这一点。

    // Defined lengths
    const lengths = [25, 15, 10, 5];
    // Some example cart corresponding to how many of each length customer has (this is from your example)
    const cart = {25: 1, 15: 1, 5: 1}
    
    for (let length of lengths) {
      //Check for each length in lengths array
      let counter = 0;
      for (let item in cart) {
        // Add the counter if there is enough in cart
        counter += Math.floor(item * cart[item] / length);
      }
      // I am console logging like you showed, but you can do whatever
      console.log(`${counter} ${length}m`)
    }
    

    输出:

    1 25m
    2 15m
    3 10m
    9 5m