Saturday, February 18, 2023

Coding Challenge #6

Daily Programmer Challenge #395 (here)

 // Given a binary array (defined as containing only values 0 and 1),
// create an array where the indices represent the lengths of the
// continuous streaks of 1's.

// Example: [0,0,1,0] => [1] (1 streak, length 1)
// [0,1,1,0] => [2] (1 streak, length 2)
// [1,0,1,0] => [1,1] (2 streaks, length 1 each)
// [1,1,1,0] => [3] (1 streak, length 3)

function calc(ary){
    var streak = 0;
    var out = [];
    for(var xint = 0, len = ary.length;xint < len;xint++){
        if(ary[xint] == 1) streak++;
        else if(streak > 0){
            out.push(streak);
            streak = 0;
        }
    }
    if(streak > 0) out.push(streak); // in case it ends in 1
    return out;
}

function test(){
    var ary = [];
    var len = Math.round(Math.random()*10) + 1;
    for(var xint = 0;xint < len;xint++)
        ary.push(Math.round(Math.random()*1));
    
    var out = calc(ary);
    console.log("Testing array: " + ary.toString() + " ===> " + out.toString());
}

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 ...