Tuesday, March 14, 2023

Coding Challenge #21

// Daily Coding Challenge #29
// 'Run-length encoding': replace repeated characters with a number before the character.
// Example: "AAABBC" -> "3A2B1C"
// Example: "ZZyaaaa" -> "2Z1y4a"
function encode(str){
    var lastChar = 0;
    var streak = 0;
    var output = "";
    for(var xint = 0, len = str.length;xint < len;xint++){
        var curChar = str.charAt(xint);
        if(lastChar != curChar){
            if(lastChar != 0){ // not the first char
                output += streak;
                output += lastChar;
            }
            streak = 1;
            lastChar = curChar;
        }else streak++;
    }
    if(streak > 0){ // log the last streak/char
        output += streak;
        output += lastChar;
    }
    return output;
}

// tests
console.log('Test #1: ' + (encode('AAABBC') == "3A2B1C" ? ("PASS") : ("FAIL")));
console.log('Test #2: ' + (encode('ZZyaaaa') == "2Z1y4a" ? ("PASS") : ("FAIL")));

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