Lego Blocks

  • + 0 comments

    Having some difficult with a valid JavaScript version. The values that are failing are when combinations get over MOD (10^9 +7) Has anybody got a JavaScript version working or can spot the error in this code? Thanks

    *(legoBlocks(8,10) on my code is giving 634608018.

    Hacker rank is giving 634597424*


    function legoBlocks(h, w) {
        // Write your code here
        let mod = (Math.pow(10, 9) + 7)
    
        //different combinations for a width when height is 1
        let t = [0];
        if (w >= 1) t.push(1)
        if (w >= 2) t.push(2)
        if (w >= 3) t.push(4)
        if (w >= 4) t.push(8)
        while (w >= 5 && t.length <= w){
            let start = t.length -4
            let arr = t.slice(start, t.length)
            let sum = arr.reduce((partialSum, a) => partialSum + a, 0)
            t.push(sum)
        }
    
        //different combinations for width given height h
        //e.g. total[height=2] is t^2, total[height=3] is t^3
        let total = t.slice()
        for (let outer=2; outer<=h; outer++) {
            for (let i = 0; i <= w; i++) {
                total[i] = (t[i] * total[i])
            }
        }
    
    
        let solid = []
        solid.length = w+1;
        solid.fill(0)
        solid[1] = 1
    
        //s[x] = total[x] - (SUM (where i starts at 1 and ends at x-1)  s[i] * total[w-i]))
        if (w>1){
            for (let ww=2; ww<=w; ww++){
                let unsolid_sum = 0;
                for (let i=1; i<ww; i++){
    
                    unsolid_sum += (((solid[i]) * (total[ww-i])))
                }
                solid[ww] = ((total[ww] - unsolid_sum))
            }
        }
    
    return solid[w] % mod
    

    }