是否存在"矩阵样式的模式"比较呢?

时间:2015-01-06 19:15:54

标签: javascript algorithm

是否存在以下决策方式的规范算法或模式:您有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编程解决这个问题。

2 个答案:

答案 0 :(得分:1)

我会循环遍历每个资源,每次计算我可以构建多少产品,假设所有其他资源都有足够的可用量,并将生产限制在最低预计金额。这基本上是资源上的 fold reduce method支持。

答案 1 :(得分:1)

嗯,这是一个示例,您可以设置任意数量的资源,将它们与密钥相关联,并设置所需的单位数量和每种资源的成本。有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/