Skip to content Skip to sidebar Skip to footer

Adding Pronumerals Together In Javascript

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) and return the following a

Solution 1:

First, let's program three little helper functions:

// exprToDict("3x + y") -> {x:3, y:1}functionexprToDict(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}functionaddDicts(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)functiondictToExpr(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)
    ))
}

Let's test it:

sword = "(3 wood) + diamond"
pickaxe = "wood + (2 diamond)"

console.log(addThings(sword, pickaxe))

Result:

(4 wood) + (3 diamond)

In order to process more than two things, modify addDicts to accept arrays:

functionaddDicts(dicts) {
    var sum = {};
    dicts.forEach(function(d) {
        for(var x in d)
            sum[x] = (sum[x] || 0) + d[x];
    });
    return sum;
}

and rewrite addThings to be:

function addThings(things) {
    return dictToExpr(
        addDicts(
            things.map(exprToDict)));
}

Example:

sword = "(3 wood) + diamond"
pickaxe = "wood + (2 diamond)"
house = "10 wood + iron"


console.log(addThings([sword, pickaxe, house]))

Solution 2:

First, parse the input string - according to your grammar - to an object to work with:

functionparseLine(input) { // pass a string like "a=(3x)+y"var parts = input.split("=");
    if (parts.length != 2) returnalert("Invalid equation");
    for (var i=0; i<2; i++) {
        var summands = parts[i].split("+");
        parts[i] = {};
        for (var j=0; j<summands.length; j++) {
            summands[j] = summands[j].replace(/^\s*\(?|\)?\s*$/g, "");
            var match = summands[j].match(/^(-?\d*\.?\d+)?\s*([a-z]+)$/);
            if (!match) returnalert("Parse error: "+summands[i]);
            var mul = parseFloat(match[1] || 1);
            if (match[2] in parts[i])
                parts[i][match[2]] += mul;
            else
                parts[i][match[2]] = mul;
         }
    }
    return parts;
}
// example:parseLine("a=(3x)+y")
// [{"a":1},{"x":3,"y":1}]

Then, apply an algorithm for solving linear equation systems on it. I leave the implementation of that to you :-)

Solution 3:

Wow, you're question has so radically changed that I'll write a completely new answer:

You can just use objects for that. Store the materials needed for the tools in key-value-maps:

vardiamondSword= {
    diamond:2,
    stick:1
};vardiamondPickaxe= {
    diamond:3,
    stick:2
};

An addition function is very simple then:

functionadd() {
    var result = {};
    for (var i=0; i<arguments.length; i++)
        for (var item inarguments[i])
            result[item] = (result[item] || 0) + arguments[i][item];
    return result;
}
// usage:add(diamondSword, diamondPickaxe)
// {"diamond":5, "stick":3}

Post a Comment for "Adding Pronumerals Together In Javascript"