Open think2011 opened 9 years ago
var obj={},
remnants={},
o,
i=0;
for(o in food){
i=material[o];
break;
}
for(o in food){
obj[o]=parseInt(material[o]/food[o]);
i=i>obj[o]?obj[o]:i;
}
for(o in food){
remnants[o]=material[o]-food[o]*i;
}
return {sum:i,remnants:remnants};
function check (food, material) {
return (function(v) {
return { sum: v, remnants: Object.keys(food).reduce(function(res, i) {
return res[i] = material[i] - v * food[i], res;
}, {}) };
})(Object.keys(food).reduce(function(res, i) {
return Math.min(res, parseInt(material[i] / food[i]));
}, Number.MAX_VALUE));
}
还是老风格,不带 if
,for
和 var
。
function check (food, material) {
var flag = !1,
sum = 0,
remnants = {};
Object.keys(food).forEach(function(key){
if(!material[key]||material[key]<food[key]) flag=!0;
sum = !sum?((material[key]/food[key])|0):Math.min(sum,(material[key]/food[key])|0);
});
if(flag) return {sum:0,remnants:material};
Object.keys(material).forEach(function(key){
remnants[key] = material[key] - sum*(food[key]||0)
});
return {sum:sum,remnants:remnants}
}
才发现在forEach里return的话是不会终止函数甚至不会终止循环的,还不如用一楼的for in
ES6来帮忙,这样效率高一点,sum=0的时候直接return不再执行
function check (food, material) {
var sum = 0,
remnants = {};
for(var key of Object.keys(food)){
if(!material[key]||material[key]<food[key]) return {sum:0,remnants:material};
sum = !sum?((material[key]/food[key])|0):Math.min(sum,(material[key]/food[key])|0);
}
Object.keys(material).forEach(function(key){
remnants[key] = material[key] - sum*(food[key]||0)
});
return {sum:sum,remnants:remnants}
}
@VaJoy 咦,哪里用到了ES6的特性,感兴趣!
@think2011 for of
弄一个不太好的:
function check (food, material) {
// 请完成这个代码
var sum = null;
for(var prop in material){
if(material.hasOwnProperty(prop) && food[prop]){
var temp = parseInt(material[prop]/food[prop]);
sum = sum == null? temp: (temp > sum ? sum : temp);
}
}
var remnants = {};
for(var prop in material){
if(material.hasOwnProperty(prop)){
remnants[prop] = material[prop] - (food[prop] ? food[prop]*sum : 0);
}
}
return {
sum: sum,
remnants: remnants
};
}
来个递归版
function check (food, material) {
// 请完成这个代码
var sum = 0;
function reducematerial(material){
if(material.rice < 1 || material.egg < 1 || material.meat < 2){
return;
}else{
++sum;
material.rice -= 1;
material.egg -= 1;
material.meat -= 2;
reducematerial(material);
}
}
reducematerial(material);
return {sum: sum, remnants: material};
}
你是一家快餐店的老板,每天营业前,你需要根据采购的食材来确定今天能够做多少份快餐: