"matrix style" 比较有模式吗?

Is there a pattern for a "matrix style" comparison?

是否存在以下决策风格的规范算法或模式:您有 n 个资源(假设现在有两个,资源 1 和资源 2)。考虑伪代码:

Request for X units, requiring resources 1 and 2 {
If (enough of resource 1)
   if (enough of resource 2)
      fulfill request for X units. 
   else (not enough of resource 2)
      partially fulfill, to max of resource 2
else (not enough of resource 1)
   if (there is enough of resource 2)
      partially fulfill, to max of resource 1. 
   else (not enough of resource 2)
      partially fulfill, to max of resource 2
}

当 n > 2 时,事情很快就会失控,并且有很多重复的代码。有没有更有效的方法来实现这个算法?

如果重要的话,我正在 Javascript 编程解决这个问题。

我会遍历每个资源,假设所有其他资源都有足够的数量,每次计算我可以从中构建多少产品,并将生产限制在所有资源中的最低预计数量。这基本上是资源的,由reduce method.

支持

好吧,这是一个示例,您可以在其中设置任意数量的资源,将它们与一个键相关联,并设置您想要的单位数量和每种资源的成本。有 2 个功能,一个使用您拥有的资源获得最大可能的单位,一个花费这些资源:

function Request(qty){
    this.quantity = qty; // quantity of units to make
    this.required = {}; // required resources
    var request = this;

    this.checkAvailability = function(resources){
        var available = request.quantity;
        var spent = {};
        var left = {};
        for(var key in request.required){ // for each required resource
            var max = Math.min(request.quantity, Math.floor(resources[key].quantity/request.required[key])) // set max as wanted quantity or available quantity if it is less than wanted
            available = Math.min(max, available) // update max of units you can make 
        }
        return available
    }

    this.spendResources = function(resources, qty){ // spend required resources
        for(var key in request.required){
            resources[key].quantity -= request.required[key]*qty;
        }
    }

}

function Resource(qty){
    this.quantity = qty;
}

var available = {
    1: new Resource(200),
    2: new Resource(140)
}

var request = new Request(7)
request.required = {1: 40, 2: 30}
var availableQty = request.checkAvailability(available)
request.spendResources(available, availableQty)
console.log(availableQty, available)

工作 Jsfiddle:http://jsfiddle.net/fk6coz8a/