在JavaScript中将Pronumerals一起添加 [英] Adding Pronumerals together in javascript
问题描述
我希望javascript能够解释以下内容(a
和b
总是会有所不同,因此这些只是一个示例)
I want javascript to be able to interpret the following (a
and b
are always going to be different, so these are just an example)
a=(3x)+y
b=x+(4y)
并返回以下内容
a+b=(4x)+(5y)
所有变量都是字符串,而不是整数,因此不能将数学应用于a
,b
,x
或y
all variables are strings and not integers so math can not be applied to a
,b
,x
or y
由于我不知道从哪里开始,所以我没有在这个特定实例上开始.
I have not started on this particular instance, due to the fact that i don't know where to start.
P.S.我没有使用jQuery的任何经验,因此,如果可能,请尝试并避免使用它
P.S. I have not had any experience with jQuery, so if possible, try and avoid it
该程序旨在帮助在游戏《我的世界》中查找原材料.例如,如果您要使用钻石剑(a
)和钻石镐(b
),则a
需要1颗木头(x
)和2颗钻石(y
),而b
需要1颗木头(x
)和3个菱形(y
).一旦我通过该程序运行它,我想回应一下,它需要2颗木材和5颗钻石.对不起,之前有任何疑问...
The program is designed to help find raw materials in the game minecraft. For example if you want a diamond sword (a
) and a diamond pickaxe (b
), a
requires 1 wood (x
) and 2 diamonds (y
), and b
requires 1 wood (x
) and 3 diamonds (y
). Once i run it through this program, i would like a response saying that it requires 2 wood and 5 diamonds. Sorry for any prior confusion...
推荐答案
首先,让我们编写三个小辅助函数:
First, let's program three little helper functions:
// exprToDict("3x + y") -> {x:3, y:1}
function exprToDict(e) {
var d = {};
e.replace(/(\d+)\s*(\w+)|(\w+)/g, function($0, $1, $2, $3) {
d[$2 || $3] = parseInt($1 || 1);
});
return d;
}
// addDicts({x:1, y:2}, {x:100, y:3}) -> {x:101, y:5}
function addDicts(a, b) {
var d = {};
for(var x in a) d[x] = a[x];
for(var x in b) d[x] = (d[x] || 0) + b[x];
return d;
}
// dictToExpr({x:1, y:2}) -> x + (2 y)
function dictToExpr(d) {
var e = [];
for(var x in d)
if(d[x] == 1)
e.push(x);
else
e.push("(" + d[x] + " " + x + ")");
return e.join(" + ")
}
一旦知道了,就可以编写主要功能了:
Once we've got that, we're ready to code the main function:
function addThings(a, b) {
return dictToExpr(
addDicts(
exprToDict(a),
exprToDict(b)
))
}
让我们对其进行测试:
sword = "(3 wood) + diamond"
pickaxe = "wood + (2 diamond)"
console.log(addThings(sword, pickaxe))
结果:
(4 wood) + (3 diamond)
为了处理两个以上的事情,请修改addDicts
以接受数组:
In order to process more than two things, modify addDicts
to accept arrays:
function addDicts(dicts) {
var sum = {};
dicts.forEach(function(d) {
for(var x in d)
sum[x] = (sum[x] || 0) + d[x];
});
return sum;
}
并将addThings
重写为:
function addThings(things) {
return dictToExpr(
addDicts(
things.map(exprToDict)));
}
示例:
sword = "(3 wood) + diamond"
pickaxe = "wood + (2 diamond)"
house = "10 wood + iron"
console.log(addThings([sword, pickaxe, house]))
这篇关于在JavaScript中将Pronumerals一起添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!