Tuesday, February 17, 2015

JavaScript

I've been learning JavaScript.  A great way to do it is to complete challenges, such as Project Euler.  One good set I found recently is at www.coderbyte.com -- a good collection of easy, medium and hard challenges. 

There is a challenge in the "easy" category, ArrayAdditionI, which seems to give beginning coders difficulty, at least based on the comments I have seen online.

When I looked at it a few weeks ago, I couldn't figure it out.  I left it and went on to other challenges.  I finally figured out a solution a couple of days ago and completed the coding today.  This solution uses binary numbers to check all possible combinations.

function ArrayAdditionI (arr) {
    var b = Math.max.apply(null, arr);
    var c = arr.indexOf(b);
    d = arr.splice(c,1);
    d = d.join("");
    d = Number(d);
    for (var x = 1; x < Math.pow(2,arr.length); x++) {
        var y = x.toString(2).split("");
        var total = 0;
        for (var z = 1; z < y.length + 1; z++ ) {
            if (y[y.length - z] === "1") {
                total += arr[z-1];
            }
        }
        if (total === d) {return true;}
    }
    return false;
}