Wednesday, February 15, 2023

Coding Challenge #3

 Daily Coding Problem #2
with an array of integers, return an array where each index of the new array is the product of all other indices of the old array.

// [1,2,3] example input
// [6,3,2] example output (6 is 2*3 (skip 1), 3 is 1*3 (skip 2), 2 is 1*2 (skip 3))

// [4,5,6] example input
// [30,24,20] example output (30 is 5 * 6 (skip 4), 24=4*6 (skip 5), 20=4*5 (skip 6))


var a = [];
function makeArray(){
    a = [];
    var len = ran(3) + 3; // array len [3,6]
    for(var xint = 0;xint < len;xint++)
        a.push(ran(9) + 1); // ran num [1,10]
}
function ran(max){ // [0,max] inclusive
    return Math.round(Math.random() * max);
}

// payload algorithm
function payload(){
    var o = [];
    for(var xint = 0, len = a.length;xint < len;xint++){
        var product = 1; // placeholder that will adapt to any value, instead of starting at value x
        for(var yint = 0, len2 = len;yint < len2;yint++){
            if(xint == yint) continue;
            product *= a[yint];
        }
        o.push(product);
    }
    return o;
}


function test(){
    makeArray();
    var o = payload();
    console.log("\n========\nArray input: " + a.toString() + "\nyields the output: " + o.toString());
}

// tests
test();
test();
test();
test();

No comments:

Post a Comment

Coding Challenge #54 C++ int to std::string (no stringstream or to_string())

Gets a string from an integer (ejemplo gratis: 123 -> "123") Wanted to come up with my own function for this like 10 years ago ...